PM Write a slideshow plugin with an object-oriented approach when you accidentally write this code:
slider.prototype.auto=function() { setinterval (this.torun,4000);//Note} Slider.prototype.toRun=function() { if(this. inow==). Aa.length-1) ...}
When the browser opens, the slide does not automatically switch as expected, and the console gives the error message:
this.aa isundefined? However I have been in the constructor slider aa gave a statement, and I realized it was setinterval (this.torun,4000 , causing the called torun method. The this pointer points to a problem.
What's the problem?
original setinterval () is a method defined under the Window object, so this does not point to the slider the instance object of the instead of the Window object.
After I found the problem, I changed the code to work. Code after the
is overwritten:
slider.prototype.auto=function() { var _this=this; // setinterval (this.torun,4000);//There is a problem, the this pointer rebind, point to the Window object SetInterval (function() {_this.torun ();},5000)// get current scope by closure }
The workaround is to store the this pointer to the Slider instance Object in the _this variable in advance, and call the prototype method by _this.torun (). (Note: The call permission for the Function property is obtained through the closure)
About the use of this
In JavaScript object-oriented programming, there are three core concepts that absolutely cannot be bypassed: one is closures, one is a prototype chain, and the other is this. You see, JavaScript source of the various overwhelming this ...
There are many articles on the Internet that have a very thorough explanation of this concept, but I feel that these articles have complicated the simple question, because the concept of this is just a word to remember.
"This is the object to which the function is located, and this points to who." ”
Understanding this sentence, you have mastered the this!
JavaScript Object-oriented this pointer