在JavaScript中讓this保持正確的指向的解決方案
對(duì)象的方法中 this 的指向
以一個(gè)代碼例子,來(lái)對(duì)切入對(duì)對(duì)象的方法中 this 的指向的討論,例子如下:
const obj = {
prop: 'I am an object',
logProp: function() {
const func = function(){
console.log(this.prop);
}();
}
};
obj.logProp()// 期望打印 obj 的 prop 屬性, I am an object
方案一:使用閉包
實(shí)現(xiàn)方式:
const obj = {
prop: 'I am an object',
logProp: function() {
let context = this;
const func = function(){
console.log(context.prop);
}();
}
};
obj.logProp()
原始代碼:
const obj = {
prop: 'I am an object',
logProp: function() {
const func = function(){
console.log(this.prop);
}();
}
};
obj.logProp()// 期望打印 I am an object
原始代碼可以理解為:
const temp = function(){
console.log(this.prop);
}
const obj = {
prop: 'I am an object',
logProp: function() {
temp(); // 相當(dāng)于在全局作用域直接調(diào)用temp函數(shù)。
}
};
obj.logProp()
瀏覽器中 JavaScript 函數(shù)執(zhí)行的方式是當(dāng)前執(zhí)行函數(shù)入棧,執(zhí)行結(jié)束則出棧。

執(zhí)行 logProp 函數(shù)后,這一函數(shù)已經(jīng)出棧,temp 函數(shù)入棧,沒有歷史棧,相當(dāng)于在全局作用域直接調(diào)用 temp 函數(shù),因此 this 指向全局對(duì)象,而不是 obj 對(duì)象。
因此在外層函數(shù) logProp 中定義一個(gè)變量 context ,保存指向 obj 的 this,在 func 中使用這個(gè)變量。logProp函數(shù)出棧時(shí),因?yàn)?func 中用到了 context,因此這個(gè)變量會(huì)留在棧內(nèi),這就是閉包。而 func 中可以通過(guò)這個(gè)變量,訪問到指向 obj 的 this。
方案二:使用箭頭函數(shù)
實(shí)現(xiàn)方式:
const obj = {
prop: 'I am an object',
logProp: function() {
const func = ()=>{
console.log(this.prop);
};
func();
}
};
obj.logProp()
箭頭函數(shù)沒有自己的 this 對(duì)象,對(duì)于普通函數(shù)來(lái)說(shuō),內(nèi)部的 this 指向函數(shù)運(yùn)行時(shí)所在的對(duì)象,但是箭頭函數(shù)沒有自己的 this 對(duì)象,內(nèi)部的 this 就是定義時(shí)上層作用域中的 this。也就是說(shuō),箭頭函數(shù)內(nèi)部的this指向是固定的,固定指向函數(shù)定義時(shí)的作用域。
方案三:換綁 this
普通函數(shù)可以使用 bind、call、apply 來(lái)?yè)Q綁this。
| API | 作用 |
|---|---|
| bind | bind()方法用于將函數(shù)體內(nèi)的this綁定到某個(gè)對(duì)象,然后返回一個(gè)新函數(shù)。 |
| call | 函數(shù)實(shí)例的call方法,可以指定函數(shù)內(nèi)部this的指向(即函數(shù)執(zhí)行時(shí)所在的作用域),然后在所指定的作用域中,調(diào)用該函數(shù)。 |
| apply | apply方法的作用與call方法類似,也是改變this指向,然后再調(diào)用該函數(shù)。唯一的區(qū)別就是,它接收一個(gè)數(shù)組作為函數(shù)執(zhí)行時(shí)的參數(shù)。 |
在本文給出的代碼示例問題中,用 bind 或 call 即可滿足需求。
用 bind 實(shí)現(xiàn)
實(shí)現(xiàn)方式:
const obj = {
prop: 'I am an object',
logProp: function() {
const func = function(){
console.log(this.prop);
}.bind(this);
func();
}
};
obj.logProp()
bind 的具體實(shí)現(xiàn):
Function.prototype.bind = function(context, args){
if(typeof this !=='function'){
throw new Error('Function.prototype.bind - what is trying to be bound is not callable')
}
const self = this;
const func = function(){
self.call(this instanceof self?self:context, args.concat(Array.prototype.slice.call(arguments)) )
}
const fNOP = function(){}
fNOP.prototype = this.prototype;
func.prototype = new fNOP();
return func;
}
用 call 實(shí)現(xiàn)
const obj = {
prop: 'I am an object',
logProp: function() {
const func = (function(){
console.log(this.prop);
}).call(this)
}
};
obj.logProp()
call 的具體實(shí)現(xiàn)
function myCall(context, ...args){
let context = context || window;
context.fn = this;
const res = eval('context.fn(...args)');
delete context.fn;
return res;
}
新創(chuàng)建的實(shí)例中this的指向
function MyClass() {
this.prop = 'I am a property';
}
const instance = MyClass();
console.log(instance); // 錯(cuò)誤,this指向全局對(duì)象而不是新創(chuàng)建的實(shí)例
解決方案:使用 new 操作符。
function MyClass() {
this.prop = 'I am a property';
}
const instance = new MyClass();
console.log(instance); // 正確,this 指向新創(chuàng)建的實(shí)例
new 操作符做了什么?
- 創(chuàng)建一個(gè)空對(duì)象,作為將要返回的對(duì)象實(shí)例。
- 將這個(gè)空對(duì)象的原型,指向構(gòu)造函數(shù)的prototype屬性。
- 將這個(gè)空對(duì)象賦值給函數(shù)內(nèi)部的this關(guān)鍵字。
- 開始執(zhí)行構(gòu)造函數(shù)內(nèi)部的代碼。
function objectFactory() {
const args = [].slice.call(arguments);
const constructor = args.shift();
const context = Object.create(constructor.prototype);
const result = constructor.apply(context, args);
const flag = result !== null && typeof constructor === "object";
return flag ? result : context;
}
let actor = _new(Person, "張三", 28);
結(jié)束語(yǔ)
到此這篇關(guān)于在JavaScript中讓this保持正確的指向的解決方案的文章就介紹到這了,更多相關(guān)JavaScript中this保持正確指向內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺析JavaScript中的array數(shù)組類型系統(tǒng)
除了對(duì)象之外,數(shù)組Array類型可能是javascript中最常用的類型了。而且,javascript中的數(shù)組與其他多數(shù)語(yǔ)言中的數(shù)組有著相當(dāng)大的區(qū)別。本文將介紹javascript中的數(shù)組Array類型,非常不錯(cuò),感興趣的朋友一起看下吧2016-07-07
小程序中實(shí)現(xiàn)獲取全部數(shù)據(jù)的圖文教程
最近在開發(fā)中遇到了一個(gè)需求,需要獲取小程序的全部數(shù)據(jù),所以這篇文章主要給大家介紹了關(guān)于小程序中實(shí)現(xiàn)獲取全部數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-11-11
簡(jiǎn)單實(shí)現(xiàn)js點(diǎn)擊展開二級(jí)菜單功能
這篇文章主要教大家簡(jiǎn)單實(shí)現(xiàn)js點(diǎn)擊展開二級(jí)菜單功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
JS實(shí)現(xiàn)頁(yè)面載入時(shí)隨機(jī)顯示圖片效果
這篇文章主要介紹了JS實(shí)現(xiàn)頁(yè)面載入時(shí)隨機(jī)顯示圖片效果,涉及javascript基于隨機(jī)數(shù)與數(shù)組的頁(yè)面元素動(dòng)態(tài)修改相關(guān)操作技巧,需要的朋友可以參考下2016-09-09
uni-file-picker文件選擇上傳功能實(shí)現(xiàn)代碼
本文介紹了uni-file-picker的基礎(chǔ)使用方法,包括選擇圖片的九宮格樣式、限制選擇的圖片數(shù)量、指定圖片類型及后綴,以及如何自定義上傳時(shí)機(jī),詳細(xì)說(shuō)明了如何通過(guò)設(shè)置不同的屬性來(lái)實(shí)現(xiàn)圖片的選擇和上傳,適用于需要在應(yīng)用中上傳圖片的開發(fā)者2024-09-09

