Callum Linington
Callum Linington

Reputation: 14417

Difference between object creations JavaScript

Is there - if any - difference between these two instantiations? What is the difference if it exists?

First:

function MyClass() {
    var vm = this;

    vm.initialise = function () { console.log('initialised'); }

    return vm; //<-- here
}

Second:

function MyClass() {
    var vm = this;

    vm.initialise = function () { console.log('initialised'); }

    //<-- here
}

Usage:

var newClass = new MyClass();

Upvotes: -1

Views: 51

Answers (1)

Quentin
Quentin

Reputation: 944528

When you use the new keyword, a constructor function function will return this by default.

Since your two options are "Use the default return value" and "Explicitly return this", there is no difference between the two approaches.


The idiomatic approach would be to not have an explicit return value, but to also not create vm in the first place and to just reference this directly.

Upvotes: 6

Related Questions