Boyang
Boyang

Reputation: 2566

In JavaScript, what does "return" do in function constructor

The following code:

function A() {
    this.method_this_outsideReturn = function() {
        console.log('method_this_outsideReturn')
    };
    return {
        method_this_insideReturn: function() {
            console.log('method_this_insideReturn')
        },
    };
}
var a = new A();
console.log(a.method_this_insideReturn()); // This would work.
console.log(a.method_this_outsideReturn()); // This wouldn't work. Warns attri_this_outsideReturn undefined

However, after commented out the return:

function A() {
    this.method_this_outsideReturn = function() {
        console.log('method_this_outsideReturn')
    };
    /*return {
        method_this_insideReturn: function() {
            console.log('method_this_insideReturn')
        },        
    };*/
}
console.log(a.method_this_outsideReturn()); // This would work now

Why is it so? What does return do in constructors? What happens when the return statement is not present?

Upvotes: 2

Views: 1281

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388406

If your constructor returns a value, the returned value will be considered as the object created, if you do not have a return statement it will assume it as return this

Upvotes: 4

Jon Wells
Jon Wells

Reputation: 4259

You're using the revealing module pattern see https://stackoverflow.com/a/5647397/874927. You are encapsulating your logic inside a function (function A()). return in a consturctor should just return this. However in your example, it has nothing to do with a constructor it's the same as returning a value from any function in Javascript.

Upvotes: 1

Dominic Green
Dominic Green

Reputation: 10258

Because you have a return, instead of receiving back and object your receiving back what ever you are returning.

So a would not be an object it would be method_this_insideReturn so you will not be able to access your local methods from a any more because they don't exist.

Im not sure why you are adding the return but it would be better to make it a local method and then access it.

   function A() {
        this.method_this_outsideReturn = function() {
            console.log('method_this_outsideReturn')
        };

        this.method_this_insideReturn: function() {
                console.log('method_this_insideReturn')
            }        

    }

console.log(a.method_this_outsideReturn());

console.log(a.method_this_insideReturn());

Upvotes: 1

Stokedout
Stokedout

Reputation: 11055

Every function/method call will have a return statement, however if it's not explicitly included it will return undefined

Therefore commenting it out in this case would return nothing.

Upvotes: -1

Related Questions