javascript - object literal notation - 是否应该使用 new

标签 javascript

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 是什么。使用 newthis 将是对 foo() 中的 foo 实例的引用。如果没有 new,this 将是全局的(可能是 window)

关于javascript - object literal notation - 是否应该使用 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751018/

相关文章:

javascript - 正确更新div中的数据AJAX(ASP.NET MVC)

javascript - 如何在 IIFE 表达式中调用函数

javascript - jQuery Mobile,透明黑色叠加效果

javascript - 延迟重复执行 Javascript 函数

javascript - Modal仅在ajax请求后触发

javascript - 如何在 react-admin 中访问自定义组件中的表单数据?

javascript - 在我的 URL 中添加参数?

javascript - 将变量从 php 传递到 Javascript 或 ajax

javascript - 默认聚焦 Ext.field.InputMask

javascript - 在新窗口中打开 SSRS URL