2

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?

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

All answers very useful but this is exactly what I'm looking for. Thanks!
1

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());

Comments

1

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.

1 Comment

The linked question is very relevant. Thx!
-1

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.

1 Comment

he is taking about constructor

Your Answer

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.