Use settimeout 1th/2 page _javascript tips in javascript classes

Source: Internet
Author: User
Tags setinterval
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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.