JavaScript

xiaoxiao2021-02-28  18

请解读一下javascript代码,并指出问题所在

var Obj=function(msg){

    this.msg=msg;

    this.shout=function(){

alert(this.msg);

}

this.waitAndShout=function(){

    setTimeout(this.shout, 2000);

    }

}

var aa=new Obj("abc");

aa.waitAndShout();

解答:

var Obj=function(msg){    this.msg=msg;    this.shout=function(){        alert(this.msg);//此this是window,因为调用shout函数的代码在setTimeout函数内部。    }    this.waitAndShout=function(){        let t = this.shout;//此this是aa,因为调用waitAndShout函数的对象是aa        setTimeout(this.shout, 2000);    }}var aa=new Obj("abc");

aa.waitAndShout();

//模拟setTimeout函数的代码

function setTimeout(func,timeSpace){     func();

}

示意图:

顺便再写一个例子,帮助理解this转移:

function Person(id,name) {     this.id = id;     this.name = name; } Person.prototype.eat = function () {     console.log(this);     console.log(this.name+"在吃");//this是谁? } Person.prototype.work = function (func) {     func();//这句话才真正调用eat函数。 } let p1 = new Person("007","张三");

p1.work(p1.eat);

转载请注明原文地址: https://www.6miu.com/read-2632643.html

最新回复(0)