【JS】this有哪些使用场景?跟C,Java中的this有什么区别?如何改变this的值?

遇到this,一直要记得这句:函数执行时,this总是指向调用该函数的对象(即:判断this所在的函数属于谁)。

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

var myObject={value:100};

myObject.getValue=function(){

    console.log(this.value);

    console.log(this);

    return this.value;}

     console.log(myObject.getValue());

7632097-e8f3e2b4d4cf1e39.png

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

var myObject={value:100};

myObject.getValue=function(){

    var foo=function(){

        console.log(this.value);

        console.log(this);    

    }    

    foo();

    returnthis.value;}

console.log(myObject.getValue());

在这里,foo属于全局对象,所以foo函数打印的this.value为undefined。


7632097-e751fdcbf969ecc1.png

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

var myObject={value:100};

myObject.getValue=function(){ 

     setTimeout(function(){

    console.log(this.value);

    console.log(this); },0);

    returnthis.value;}

console.log(myObject.getValue());

7632097-e92cde2a87f9d1ec.png

所以,如果要得到想要的结果,就要这样写了吧:

myObject.getValue=function(){

let self=this;//用一个self保存当前的实例对象,即

myObjectsetTimeout(function(){

    console.log(self.value);

    console.log(self);    },0);

    returnthis.value;}

console.log(myObject.getValue());

结果如下:


7632097-75ea125ec83d38b0.png

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

var myObject={value:100};myObject.getValue=function(){

// let self=this;//因为用了箭头函数,所以这句不需要了

setTimeout(()=>{

console.log(this.value);

console.log(this); },0);

returnthis.value;}

console.log(myObject.getValue());  //结果如上

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

var oneObject = function(){

    this.value=100;};

    var myObj = newoneObject();

console.log(myObj.value); //100

4、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。执行代码如下:


7632097-d09908e308df2919.png

猜你喜欢

转载自blog.csdn.net/weixin_34220834/article/details/87804277