Use setTimeout page 1/2 in the Javascript class

Source: Internet
Author: User

Recently I encountered a javascript question. The content is as follows:

Try to implement Javascript in the annotation SectionCode, You can add more
Code (if it cannot be implemented, describe the reason why it cannot be implemented ):

VaR OBJ = function (MSG ){
This. MSG = MSG;
This. Shout = function (){
Alert (this. msg );
}

This. waitandshout = function (){
// Execute the above shout method every five seconds
}
}

VaR testobj = new OBJ ("Hello, world! ");
Testobj. Shout (); frankly speaking, I didn't have the experience of using setTimeout/setinterval in Javascript classes before, so I thought it was unfeasible at first. However, after careful consideration, we can find that this can be achieved. To put it another step, it is very easy to execute a specific statement every five seconds. For example, if you do not consider other factors, the function in the question can be written as follows:

This. waitandshout = function (){
SetTimeout ('this. Shout () ', 5000 );
} After running, everyone will realize that this variable cannot be found. But why? It will soon be realized that setTimeout/setinterval is a method of the window object, so it can also be written as window. setTimeout/window. setinterval, then the preceding this. shout () is very easy to understand why it cannot be executed, because it actually calls window. shout ().

After knowing the cause, it will be very easy to solve. You only need to bind the object to the window object (I am excited about the interesting JavaScript Object mechanism ). Then, make a small modification to the above function:

This. waitandshout = function (){
Window. OBJ = this;
SetTimeout ('obj. Shout () ', 5000 );
. Actually

SetTimeout ('obj. Shout () ', 5000); equivalent

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.