About delayed execution and variable promotion

question: how to understand the delay execution of setTimeout
description: I want to see the specific use of the new method by changing the construction properties of the function prototype, but after triggering changAs () , I found that the constructor triggered by console.log (new As ()); before the changAs () statement has been changed

.

clipboard.png

answer:

1. setTimeout
2. chrome,console.log(),i/o,,,chromeconsole.log(),,

then I intend to use setTimeout trigger delay execution to generate async, but it doesn"t work

eager answer:

  1. Why is setTimeout invalid here
  2. hopes to explain why it appears and triggers execution first, but the result is still changed

Thank you very much

Code:

function As() {
    c = function(){
        console.log("no.1");
    };
    a = 1 ;
    a = 2;
    return this;
};
As.prototype.As = "no.1";
As.prototype.c = function(){
    console.log("no.1");
};
console.log(As);
console.log(typeof(As));
var s1 = As;
console.log(s1);        //
console.log(As());    //window,returnundefined,
console.log(As.prototype);
As().c();        //no.1        //,underined.c()
console.log(As().a);        // ,a,,window
console.log(new As());    //
new As().c();    //no.1
new new As().c();    //no.1
console.log(new As().As);    //no.1
function changeAs(){
console.log("");
As.prototype.constructor = function(){
    this.d = function(){
        console.log("no.1");
    }
    return this;
}}
setTimeout(changeAs(), 2000);
console.log(new As());
Mar.20,2021

look at the function signature of setTimeout first.

setTimeout({String|Function} code,{number} [delay]);

the first parameter of setTimeout is function

setTimeout(changeAs(), 2000);

the code of the landlord passes in the return value of changeAs. This should be void

you can try to change it to this

setTimeout(changeAs, 2000);

or

setTimeout(function(){
  changeAs();
}, 2000);

question 2:

https://developer.mozilla.org.

 Object 1true"test"

constructor is a constructor in other languages, the equivalent of a hook, triggered when new, but in js. Will not play this role.. Should directly AS = function () {} to change the constructor

it is suggested that the landlord should add more basic knowledge


var obj={};
console.log(obj);
obj.test='test';

you run the above code to see the result

Menu