js中this的四种使用场景

最近读到了一篇介绍js中this的四种使用场景的文章,感受总结的很好,因此我认真读了读,而且动手实践了其中的demo,与你们共享。原文连接:
https://github.com/alsotang/n...
遇到this,一直要记得这句:函数执行时,this老是指向调用该函数的对象(即:判断this所在的函数属于谁)。node

一、函数有所属对象,则指向所属对象git

var myObject={
    value:100
};
myObject.getValue=function(){
    console.log(this.value);
    console.log(this);
    return this.value;
}
console.log(myObject.getValue());

这里的getValue属于对象myObject,因此this就指向myObject,执行结果以下:
clipboard.pnges6

二、函数没有所属对象时,就指向全局对象(window或global)github

var myObject={
    value:100
};
myObject.getValue=function(){
    var foo=function(){
        console.log(this.value);
        console.log(this);
    }
    foo();
    return this.value;
}
console.log(myObject.getValue());

在这里,foo属于全局对象,因此foo函数打印的this.value为undefined。
clipboard.pngapp

写到这里,我又想起setTimeout和setInterval方法也是属于全局对象的,因此在这两个函数体内this是指向全局的,因此也是这种状况,以下:less

var myObject={
    value:100
};
myObject.getValue=function(){
    setTimeout(function(){
        console.log(this.value);
        console.log(this);
    },0);
    return this.value;
}
console.log(myObject.getValue());

执行结果以下:
clipboard.png函数

因此,若是要获得想要的结果,就要这样写了吧:this

myObject.getValue=function(){
    let self=this;//用一个self保存当前的实例对象,即myObject
    setTimeout(function(){
        console.log(self.value);
        console.log(self);
    },0);
    return this.value;
}
console.log(myObject.getValue());

结果以下:
clipboard.pngspa

这又让我想起来了es6中箭头函数的妙用了(这个this绑定的是定义时所在的做用域,而不是运行时所在的做用域;箭头函数其实没有本身的this,因此箭头函数内部的this就是外部的this)(可详看es6教程:http://es6.ruanyifeng.com/#do...箭头函数),以下:code

var myObject={
    value:100
};
myObject.getValue=function(){
    // let self=this;//由于用了箭头函数,因此这句不须要了
    setTimeout(()=>{
        console.log(this.value);
        console.log(this);
    },0);
    return this.value;
}
console.log(myObject.getValue());

执行结果同上:
clipboard.png

三、使用构造器new一个对象时,this就指向新对象:

var oneObject=function(){
    this.value=100;
};
var myObj=new oneObject();
console.log(myObj.value);

这里的this就指向了new出来的新对象myObj,执行结果以下:
clipboard.png

四、apply,call,bind改变了this的指向

var myObject={
    value:100
}
var foo=function(){
    console.log(this);
    console.log(this.value);
    console.log("...............");
}
foo();
foo.apply(myObject);
foo.call(myObject);
var newFoo=foo.bind(myObject);
newFoo();

foo原本指向全局对象window,可是call,apply和bind将this绑定到了myObject上,因此,foo里面的this就指向了myObject。执行代码以下:
clipboard.png

相关文章
相关标签/搜索