看了《JavaScript高级程序设计》中关于对象的介绍,记录一下对于其中有些地方的疑惑。

  1. 使用构造函数创建对象时,prototype中如果定义一个属性指向函数,在函数中引用this,为什么this是指向构造函数而不是prototype对象?

试验:

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

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

按照书上的讲解,test实例的结构应该是如下的(伪代码):

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

__proto__既然和obj同一层级的,那getSuperValue应该就和testValue是有同样的表现才对呀,为什么getSuperValue可以读取到property的值呢?


neo_seele
33 声望0 粉丝