【问题标题】:JavaScript constructors with and without new operator带有和不带有 new 运算符的 JavaScript 构造函数
【发布时间】:2016-01-21 23:22:33
【问题描述】:

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

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

【问题讨论】:

  • 第二个没有创建实例。它将属性添加到window 对象。如果您尝试在严格模式下运行该代码,它将崩溃,因为您将属性分配给undefined

标签: javascript constructor new-operator


【解决方案1】:

这“有效”是因为没有newthis 在浏览器上下文中解析为window,因此将window 对象的title 属性设置为title 参数。

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

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

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

【讨论】:

  • 我全部在 Node 中运行,而不是在浏览器中。如果我们将windowglobal 互换,那么同样的逻辑在那里工作?
  • @Alexander 是的,同样的事情。
猜你喜欢
  • 2019-04-26
  • 1970-01-01
  • 2014-01-11
  • 2023-03-31
  • 2019-09-26
  • 2014-01-22
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多