0

I have some questions regarding how function in javascript works.

Case 1:

function myFunction(){
    var _instance = this;

    _instance.show = function() {
        return "hi";
    }

    return function(){ return "hello"; };
}

var t2 = new myFunction();
alert(t2()); //this will show hello
alert(t2.show()); //this will cause error t2.show is not a function

Case 2:

function myFunction(){
    var _instance = this;

    _instance.show = function() {
        return "hi";
    }

    return 5;
}

var t2 = new myFunction();
alert(t2.show()); //this will show hi
alert(t2());//this will cause error t2 is not a function

In case 1, I understand that it returned anonymous function. That's why I can call t2(), but not t2.show

In case 2, I expected it to return a number 5, but it returned an instance of myFunction. That's why I can call t2.show(), but not t2().

That's strange. Could any please explain why it behaved like that?

Thanks.

beckham12a18
  • 3
  • 1
  • 5

0 Answers0