看了《JavaScript高级程序设计》中关于对象的介绍,记录一下对于其中有些地方的疑惑。
- 使用构造函数创建对象时,
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
的值呢?
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。