【发布时间】:2014-01-23 21:37:57
【问题描述】:
名称为“name”的属性声明始终是一个空字符串,无论我如何强制(硬编码)一个值。奇怪的是,这似乎只发生在 Chrome 和 Firefox 中。 IE 工作得很好,我什至没有为 IE 构建这个。
这里有一个小sn-p来重现这个问题:
var fn = function() {
this.name = "Hello World"
this.foo = "bar"
}
// Create a blank function.
var obj = function() {};
// replacing the code below with 'var o = new fn()' doesn't make a difference.
var o = Object.create(fn.prototype);
fn.apply(o);
for (var i in o) {
// This line will print:
// name = Hello World
// foo = bar
console.log(i + ' = ' + o[i]);
// Apply them to the 'empty' function.
obj[i] = o[i];
}
console.log(obj.name); // prints ""
console.log(obj.foo); // prints "bar"
// Hardcode a value, just because I'm aggresive and frustrated.
obj.name = "test?"
console.log(obj.name); // still prints empty string :(
我对听到对象构造的替代方案不感兴趣,我只想知道为什么这个特定的实现在 Chrome 和 FF 中不起作用,而在所有 IE 版本中都起作用,包括 11 .
【问题讨论】:
-
很明显是因为
obj是一个函数,而一个函数已经有name属性,它是内置在原型中的,即使你没有给函数起名字,你也可以'以后不要更改函数名称。 -
^^ 是的,试试
var obj = function lulz() {},你会看到“lulz”。 -
它与 IE 一起工作的原因是因为 IE 很奇怪。 :)
标签: javascript internet-explorer google-chrome inheritance