Alexander
Alexander

Reputation: 255

JavaScript constructors with and without new operator

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

Upvotes: -1

Views: 69

Answers (1)

meder omuraliev
meder omuraliev

Reputation: 186562

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.

Upvotes: 2

Related Questions