欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在JavaScript中讓this保持正確的指向的解決方案

 更新時(shí)間:2024年01月19日 11:11:47   作者:Tiffany  
這篇文章主要介紹了關(guān)于在 JavaScript 中如何讓 this 保持正確的指向的解決方案,文中給大家介紹了三種解決方案,使用閉包,使用箭頭函數(shù)和換綁 this這三種方法,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下

對(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ù)入棧,沒(méi)有歷史棧,相當(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è)變量,訪問(wèn)到指向 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ù)沒(méi)有自己的 this 對(duì)象,對(duì)于普通函數(shù)來(lái)說(shuō),內(nèi)部的 this 指向函數(shù)運(yùn)行時(shí)所在的對(duì)象,但是箭頭函數(shù)沒(méi)有自己的 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作用
bindbind()方法用于將函數(shù)體內(nèi)的this綁定到某個(gè)對(duì)象,然后返回一個(gè)新函數(shù)。
call函數(shù)實(shí)例的call方法,可以指定函數(shù)內(nèi)部this的指向(即函數(shù)執(zhí)行時(shí)所在的作用域),然后在所指定的作用域中,調(diào)用該函數(shù)。
applyapply方法的作用與call方法類似,也是改變this指向,然后再調(diào)用該函數(shù)。唯一的區(qū)別就是,它接收一個(gè)數(shù)組作為函數(shù)執(zhí)行時(shí)的參數(shù)。

在本文給出的代碼示例問(wèn)題中,用 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)鍵字。
  • 開(kāi)始執(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)文章

最新評(píng)論