我对 JavaScript 还很陌生,实际上我正在教程中研究反射概念。
所以我有以下代码:
/* REFLECTION AND EXTEND:
REFLECTION: An object can look at itself listing and changing its properties and methods. So it means that a JavaScript object have the ability to look at its own properties and methods. We can use this feature of the JavaScript language to implement a very userful pattern called EXTEND.
*/
/* This is a generic person object that have 'firstname' and 'lastname' peropertiest setted on a 'Default' value. This generic person object provide also a getFullName() method that return the concatenation of the firstname and the lastname
*/
var person = {
firstname: 'Default',
lastname: 'Default',
getFullName: function() {
return this.firstname + ' ' + this.lastname;
}
}
/* This john object represent a specific person but do not provide the getFullName() method: */
var john = {
firstname: 'John',
lastname: 'Doe'
}
// don't do this EVER! for demo purposes only !!!
/* This set the 'person' object on the proto variable of the john object. So from this john object I can also use the getFullName() method defined for the generic person object: */
john.__proto__ = person;
// Now, we are going to see an example of the use of reflection in JavaScript:
for (var prop in john) { // Iterate on all the properties into the john object (prop is the current property during the iteration)
if (john.hasOwnProperty(prop)) {
// propo is the current property name and john[prop] is the related value of this property into the john object:
console.log(prop + ': ' + john[prop]);
}
}
代码非常简洁,注释解释了它的作用。
因此,我有一个通用的 person 对象,它提供 getFullName() 方法,并且我还有代表特定人员的 john 对象但这还没有定义 getFullName() 方法。
然后我这样做:
john.__proto__ = person;
也就是说 person 对象是 john 对象的原型(prototype),因此这意味着 john 对象继承自 人对象。因此,我希望现在 john 对象也可以通过 getFullName() 方法进行访问。
然后,我使用反射来迭代 john 对象,并打印该对象的所有属性。
我得到这个结果:
firstname: John
lastname: Doe
这对我来说似乎很奇怪,因为正如我在教程中看到的那样,我也希望看到这个属性:
getFullName: function() {
return this.firstname + ' ' + this.lastname;
}
因为现在我可以访问它了。
为什么我看不到?我缺少什么?有什么问题吗?
最佳答案
正如人们所看到的,Juhana 已经在评论中回答了这个问题,但我想添加我的解释。
当你这样做时:
john.__proto__ = person;
我想说它连接两个对象,因为对象 john
具有 person
的原型(prototype)。因此 john 可以访问 person 对象中的所有可用属性。
这仍然不会将 person 对象的属性添加到对象 john,但它们之间按照 __proto__
建立连接。因此,john 仍然拥有自己的 props,并且可以访问 person 对象中的方法。
此条件:
if (john.hasOwnProperty(prop)) {
不允许它记录其原型(prototype)的属性。
hasOwnProperty
限制迭代中对当前对象的属性访问。
关于javascript - 为什么当我在此 JavaScript 对象上使用反射时,我看不到其原型(prototype)对象中定义的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34528268/