I am a novice. I encountered a little confusion when learning javascript
timer. It may be a clich problem, but I still want to ask the elders. The problem and code are as follows:
var Cat = function() {
var o = {
say: function() {
console.log("say something");
}
}
setInterval(function(){
o.say()
}, 1000)
return o
}
var cat = Cat()
cat.say = function() {
console.log("Hello");
}
problem description:
I defined a Cat
class (factory mode used), and then this class has a method say ()
, and a setInterval
executes the "method", then instantiates the class and redeclares the say ()
method.
my confusion:
is that the output is" Hello", not the method in the class I defined in the first place. This place doesn"t really understand
personal understanding:
because the return function passed in setInterval
is a method, in fact, that o refers to the instantiated instance object, not the original class?
but I feel like I understand a little, but I don"t understand it, or I don"t understand it at all. I hope you seniors can have a detailed answer on how to correctly and clearly understand the running process of this code.