What is the difference in work of the following two chunks of code. Both seems to work similarly (I know that first is correct and second is not, but what the difference is?).
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();
And the same code, but constructor with return this
and creating an instance of object without new
operator
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();
Both returns the same result:
Playing Dark Side of the Cheese - Pink Mouse
1 Answer 1
This "works" because this
without new
resolves to window
in a browser context and thus sets the title
property of the window
object to the title
parameter.
You should use new
so it's constructed in the right context and properly creates a new object with its own properties.
function Album() { alert(this==window); }; x = Album(); // true
function Album() { alert(this==window); }; x = new Album(); // false
So if you made another instance, this.title
would override the previous and so forth, and you wouldn't have any standalone object to store title
with.
-
I ran all in Node, not in browser. So same logic work there if we interchange
window
withglobal
?Alexander– Alexander2016年01月21日 23:33:02 +00:00Commented Jan 21, 2016 at 23:33 -
Explore related questions
See similar questions with these tags.
window
object. If you try running that code in strict mode, it will crash since you'll be assigning properties toundefined
.