-1

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
asked Jan 21, 2016 at 23:22
2
  • stackoverflow.com/questions/32978852/… Commented Jan 21, 2016 at 23:24
  • The second one doesn't create an instance. It adds the properties to the window object. If you try running that code in strict mode, it will crash since you'll be assigning properties to undefined. Commented Jan 21, 2016 at 23:25

1 Answer 1

2

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.

answered Jan 21, 2016 at 23:25
2
  • I ran all in Node, not in browser. So same logic work there if we interchange window with global? Commented Jan 21, 2016 at 23:33
  • @Alexander Yes, same thing. Commented Jan 21, 2016 at 23:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.