this

Node腳本中g(shù)lobal和this是區(qū)別對(duì)待的,而Node命令行中,兩者可等效為同一對(duì)象

函數(shù)正常被調(diào)用(不帶new)時(shí),里面的this指向的是全局作用域

foo = 'bar';
function testThis() {
  this.foo = "foo";
}
console.log(this.foo); //logs "bar"
testThis();
console.log(this.foo); //logs "foo"

還有個(gè)例外,就是使用了"use strict";。此時(shí)this是undefined。

foo = "bar";
function testThis() {
  "use strict";
  this.foo = "foo";
}
console.log(this.foo); //logs "bar"
testThis();  //Uncaught TypeError: Cannot set property 'foo' of undefined 

在JavaScript中,函數(shù)可以嵌套函數(shù),也就是你可以在函數(shù)里面繼續(xù)定義函數(shù)。但內(nèi)層函數(shù)是通過閉包獲取外層函數(shù)里定義的變量值的,而不是直接繼承this。

function Thing() {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
    var info = "attempting to log this.foo:";
    function doIt() {
        console.log(info, this.foo);
    }
    doIt();
}

var thing = new Thing();
thing.logFoo();  //logs "attempting to log this.foo: undefined"

將實(shí)例的方法作為參數(shù)傳遞,可以將方法理解為堆中的區(qū)域,變量為指向該區(qū)域的指針,當(dāng)a.c -> b,d.e = a.c,變成了d.e ->b,你確定以前的this還是那個(gè)this嗎?記住,對(duì)象間的賦值是引用。

function Thing() {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {  
    console.log(this.foo);   
}

function doIt(method) {
    method();
}

var thing = new Thing();
thing.logFoo(); //logs "bar"
doIt(thing.logFoo); //logs undefined
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容