JavaScript prototype 疑惑
文章目录
看了《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的值呢?
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论