我必须承认,JavaScript 有时会有奇怪的行为。
var Npc = function() {
this.name='Hello world';
}
Npc.attr='my new attribute';
console.log('>>>>'+Npc.attr); // my new attribute
console.log('>>>>'+Npc.name); // '' ????
var data = new Npc();
console.log('>>>>>' + data.attr); // undefined
console.log('>>>>>' + data.name); // Hello world
我听起来很奇怪。 如果我能理解 .name 差异(实例与文字),我就无法理解“attr”行为。
这是一头牛吗?但是使用 Node.js 调试器我确实看到了 attr 属性!?
哇...
最佳答案
这很正常。
var Npc = function() {
this.name='Hello world';
}
是一个函数构造函数,在执行该函数之前不会发生任何事情并且名称不存在,这是有意义的。
所以此时仅定义了 attr。
var data = new Npc();
console.log('>>>>>' + data.attr); // undefined
console.log('>>>>>' + data.name);
var data = new Npc();
返回一个新对象,这是有意义的,因为您正在使用 new
。
如果你想访问 attr,你需要在新对象中找到对 Npc 的引用
data.constructor.attr
是你可以找到 attr 的地方
编辑
- 纠正了 data.constructor.attr 上的小错误
关于javascript - JS 墙上的又一 block 砖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22561849/