JavaScript_this的转移

请解读一下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);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值