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?

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
Boyang
  • 2,520
  • 5
  • 31
  • 49

4 Answers4

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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());
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
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.

Community
  • 1
  • 1
Jon Wells
  • 4,191
  • 9
  • 40
  • 69
-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.

Stokedout
  • 11,003
  • 5
  • 24
  • 30