【发布时间】: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