JavaScript面试题系列_this的转移

说明一下:
         如果对this没有了解时,最好先阅读这篇文章:javascript_this的理解,否则,下面的描述会很难理解,甚至会打击你的积极性。

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


var Obj=function(msg){

    this.msg=msg;

    this.shout=function(){

alert(this.msg);

}

this.waitAndShout=function(){

    setTimeout(this.shout, 2000);

    }

}

扫描二维码关注公众号,回复: 5561983 查看本文章

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);

//要判断this是谁,一定要看this所属函数的 “调用” 对象(记住:调用)。
--------------------- 
作者:田江 
来源:CSDN 
原文:https://blog.csdn.net/jiang7701037/article/details/79314864 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_40888956/article/details/88415259
今日推荐