Ting Lee
Ting Lee

Reputation: 33

add method with dot and with prototype

I have the following code

(function() {

    var sayHello;

    sayHello = (function() { 
        //add method to SayHello?
        SayHello.load = function() {
            var s = new SayHello();
            return s;
        };
        //SayHello constructor
        function SayHello() {
            this.text = "hello";
        }
        //add method to SayHello
        SayHello.prototype.print = function(selector){
            var elm = document.querySelector(selector);
            elm.innerHTML = this.text;
        };

        return SayHello;

    })();

    window.s = sayHello;

})();

I don't understand why the code works when assigning function to "SayHello.load" but not to "SayHello.prototype.load". And assigning function to "SayHello.prototype.print" can work but to "SayHello.print" cannot.

Upvotes: 2

Views: 732

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

I don't understand why the code works when assigning function to "SayHello.load" but not to "SayHello.prototype.load".

SayHello.load is not same as SayHello.prototype.load since in the first one you are adding the property to the SayHello object and in the second one you are adding it to the prototype of SayHello.

So when you do

var obj1 = new SayHello();

In the first case (SayHello.load) obj1 will not have load property, but in second case (SayHello.prototype.load) it will have.

Now this means when you did SayHello.load, you basically worked on a variable whose initialization was hoisted to the top of the function. In other words, variable SayHello was already initialized but the constructor SayHello wasn't defined yet.

Which is why you cannot do SayHello.prototype.load before

function SayHello() 
{
    this.text = "text";  
}

but you can do SayHello.load since it doesn't involve constructor of SayHello.

Upvotes: 1

Related Questions