Recently encountered a Javascript exam, which reads as follows:
Try to implement the Javascript code in the annotation section to add more anywhere else
Code (if not implemented, explain why it cannot be implemented):
var Obj = function (msg) {
this.msg = msg;
This.shout = function () {
alert (this.msg);
}
This.waitandshout = function () {
Perform the above shout method after five seconds
}
}
var testobj = new OBJ ("hello,world!");
Testobj.shout () Frankly, I didn't use the Settimeout/setinterval experience in Javascript, so I started off thinking it was not possible. But after careful deliberation, it can be realized. To step back, executing a paragraph every five seconds is very easy to implement. For example, without considering other factors, the function in the topic can be written as follows:
This.waitandshout = function () {
SetTimeout (' This.shout () ', 5000);
After running, anyone will realize that this variable is not found. But this is why, it is very soon to realize that Settimeout/setinterval is actually a method of window object, so can also be written as Window.settimeout/window.setinterval, then the above This.shout () is very easy to understand why it cannot be performed because it actually calls Window.shout ().
Knowing the cause is a lot easier to solve, as long as you bind the object to the Window object (I'm excited about the interesting object mechanism of Javascript). So, the above function makes a minor modification:
This.waitandshout = function () {
Window. OBJ = this;
SetTimeout (' Obj.shout () ', 5000);
So it's OK. As a matter of fact
SetTimeout (' Obj.shout () ', 5000); equivalent to
Current 1/2 page
12 Next read the full text