鍍金池/ 問(wèn)答/HTML/ JavaScript prototype 中屬性賦值為函數(shù)后有關(guān) this 的疑

JavaScript prototype 中屬性賦值為函數(shù)后有關(guān) this 的疑惑

看了《JavaScript高級(jí)程序設(shè)計(jì)》中關(guān)于對(duì)象的介紹,關(guān)于prototype中屬性賦值為函數(shù)后有關(guān)this疑惑。

使用構(gòu)造函數(shù)創(chuàng)建對(duì)象時(shí),prototype中如果定義一個(gè)屬性指向函數(shù),在函數(shù)中引用this,為什么this是指向構(gòu)造函數(shù)而不是prototype對(duì)象?

試驗(yàn):

function SuperType() {
    this.property = 'value in SuperType'
    this.obj = {
        testThis: function() {
            console.log(this)
            console.log(this.testValue)
            console.log(this.property)
        },
        testValue: 'value in SuperType.obj',
    }
}

SuperType.prototype.getSuperValue = function() {
    console.log(this)
    return this.property
}

const test = new SuperType()

test.obj.testThis()
// output:
// { testThis: [Function: testThis], testValue: 'test' }
// value in SuperType.obj
// undefined

const r = test.getSuperValue()
console.log(r)
// output:
// SuperType {
//  property: true,
//  obj: { testThis: [Function: testThis], testValue: 'value in SuperType.obj' }
// }
// value in SuperType

按照書上的講解,test實(shí)例的結(jié)構(gòu)應(yīng)該是如下的(偽代碼):

test = {
    __proto__: {
        constructor: SuperType,
        getSuperValue: function() { ... },
    },
    obj: {
        testThis: function() { ... },
        testValue: 'value in SuperType.obj',
    },
    property: 'value in SuperType',
}

__proto__既然和obj同一層級(jí)的,那getSuperValue應(yīng)該就和testValue是有同樣的表現(xiàn)才對(duì)呀,為什么getSuperValue可以讀取到property的值呢?

回答
編輯回答
綰青絲

test列出的是你這樣,但你打印下test.obj看看發(fā)生了什么。

2017年11月27日 18:43
編輯回答
心悲涼

當(dāng)運(yùn)行到test.getSuperValue()時(shí),會(huì)執(zhí)行console.log(this),這時(shí)這個(gè)this指向的是test實(shí)例,所以,r的值是value in SuperType。

2018年5月29日 06:04
編輯回答
撿肥皂

構(gòu)造函數(shù)和prototype中的this都是指向?qū)?lái)創(chuàng)建的實(shí)例

2018年5月30日 15:07
編輯回答
司令

首先,“__proto__既然和obj同一層級(jí)的,那getSuperValue應(yīng)該就和testValue是有同樣的表現(xiàn)才對(duì)呀”,沒(méi)有這種規(guī)則的。

其次,this 要么為 undefined,要么指向一個(gè)對(duì)象,只有這兩種情況。所以不會(huì)指向構(gòu)造函數(shù)。

當(dāng) this 指向一個(gè)對(duì)象時(shí),具體指向誰(shuí),取決于函數(shù)定義和調(diào)用的方式,與定義在哪兒無(wú)關(guān)。

具體有六種情況,看這里吧

2017年9月17日 18:11