带或不带 new 运算符的 JavaScript 构造函数

标签 javascript constructor new-operator

下面两段代码的工作有什么区别?两者似乎工作相似(我知道第一个是正确的,第二个不是,但有什么区别?)。

function Album(title, artist) {
    this.title = title;
    this.artist = artist;
    this.play = function() {
        console.log("Playing " + this.title + " - " + this.artist);
    };
}
var darkside = new Album("Dark Side of the Cheese", "Pink Mouse");
darkside.play();

代码相同,但构造函数带有 return this 并创建一个没有 new 运算符的对象实例

function Album(title, artist) {
    this.title = title;
    this.artist = artist;
    this.play = function() {
        console.log("Playing " + this.title + " - " + this.artist);
    };
    return this;
}
var darkside = Album("Dark Side of the Cheese", "Pink Mouse");
darkside.play();

两者返回相同的结果:

Playing Dark Side of the Cheese - Pink Mouse

最佳答案

这个“有效”,因为没有 newthis 会解析为浏览器上下文中的 window ,从而设置 title > 将 window 对象的属性传递给 title 参数。

您应该使用new,以便它在正确的上下文中构造并正确创建具有自己属性的新对象。

function Album() { alert(this==window); }; x = Album(); // true 
function Album() { alert(this==window); }; x = new Album(); // false

因此,如果您创建另一个实例,this.title 将覆盖前一个实例,依此类推,并且您将没有任何独立对象来存储 title

关于带或不带 new 运算符的 JavaScript 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936305/

相关文章:

javascript - 如何从矩形点计算旋转 Angular ?

c# - 如何清除 javascript 中 OnUnload 事件中的 asp.net session 值

c++ - 这个指针在C++中突然变成了0x0

c++ - 如果一个类包含另一个类的对象,并且所有类都通过构造函数初始化,那么初始化如何工作?

c++ - 分配 C++ 对象数组

javascript - Nuxt 打开链接到模态

c++ - 在大块中进行分页时,堆分配是否更有效?

c++ - 在循环中使用新指针填充 map (C++)

C++分配数组语法问题

javascript - 无法在html中调用.js(使用knockout)