下面两段代码的工作有什么区别?两者似乎工作相似(我知道第一个是正确的,第二个不是,但有什么区别?)。
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
最佳答案
这个“有效”,因为没有 new
的 this
会解析为浏览器上下文中的 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/