當前位置:
首頁 > 最新 > js中this的四種使用場景

js中this的四種使用場景

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,執行結果如下:

2、函數沒有所屬對象時,就指向全局對象(window或global)

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。

寫到這裡,我又想起setTimeout和setInterval方法也是屬於全局對象的,所以在這兩個函數體內this是指向全局的,所以也是這種情況,如下:

var myObject={

value:100

};

myObject.getValue=function(){

setTimeout(function(){

console.log(this.value);

console.log(this);

},0);

return this.value;

}

console.log(myObject.getValue());

執行結果如下:

所以,如果要得到想要的結果,就要這樣寫了吧:

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

結果如下:

這又讓我想起來了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);

return this.value;

}

console.log(myObject.getValue());

執行結果同上:

3、使用構造器new一個對象時,this就指向新對象:

var oneObject=function(){

this.value=100;

};

var myObj=new oneObject();

console.log(myObj.value);

這裡的this就指向了new出來的新對象myObj,執行結果如下:

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。執行代碼如下:


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 貳零一八 的精彩文章:

vue腳手架搭建

TAG:貳零一八 |