当我调用以下两个构造函数时,它们的工作原理是相同的(据我所知):
var x2z = new xyz('ralph');
我是否编写这样的构造函数:
function xyz(name) {
return {
name: name,
x:1,
get y() {return this.x+1},
get z() {return this.y+1}
}
}
或者如果我已经声明了:
function xyz(name) {
this.name = name;
this.x = 1;
Object.defineProperties(this, {
"y": {"get": function() {return this.x+1}}
}),
Object.defineProperties(this, {
"z": {"get": function() {return this.y+1}}
})
}
第二种形式是随处可见的形式。但为什么第一个有效呢? new 关键字是否被忽略并返回对象文字?
两者有何关系?如果有人能给我指出一个引用资料,那就太好了;我可以在对象上找到很多东西,但我在第一个表单上没有找到任何东西。
我组装了一个简单的 jsperf,文字版本稍微快一些,但如果它只是一个奇怪的东西,还不足以使用它。 (jsperf example)。但它似乎比更常用的引用“this”的构造函数更简单。
最佳答案
MDN 有关于"new"的非常好的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created [initially] is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
关于javascript - 仅返回对象文字的构造函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27002576/