function foo() {
return {a:9};
}
var bar = foo();
bar.a //returns 9
或
function foo() {
return {a:9};
}
var bar = new foo();
bar.a // returns 9
据我所知,new 不与对象字面量符号一起使用,但 new 怎么能与它一起使用呢?另外,为什么可以使用新对象访问原型(prototype),但不能使用对象字面量表示法?
编辑:
我现在明白了,如果其他人偶然发现这个问题/疑问,这可能会帮助您理解它:
function foo() {
this.a = "LOL";
return "WTF";
};
var bar = new foo(); // bar = [Object object]
var c = foo(); // c = "WTF"
window.a // "LOL"
另请阅读已接受的答案。
最佳答案
在这种情况下使用 new
与您返回的内容无关,而是 foo()
内部的 this
是什么。使用 new
,this
将是对 foo()
中的 foo 实例的引用。如果没有 new,this
将是全局的(可能是 window
)
关于javascript - object literal notation - 是否应该使用 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751018/