Search code examples
javascriptjqueryprototype-oriented

What's the difference between these codes?


function Demo() {
   this.show1 = function() { alert(1) }
}

Demo.prototype.show2 = function() { alert(2) }

var d = new Demo
d.show1()
d.show2()

show1 and show2 can both alert number.

Is there any difference between these two?


Solution

  • Yes, if you initialize that method inside the constructor, e.g. (this.method = function () {};), all of your 1000 object instances will have a function object as own property.

    Well, it's the most lightweight way to go, let's say you have a method in the prototype of certain constructor, and you create 1000 object instances, all those objects will have your method in their prototype chain, and all of them will refer to only one function object.

    In the second case, only those objects, which get created after the Demo.prototype.show2 = function(){alert(2)} will get the code. :)

    Example

    Your code

    function Demo(){
       this.show1 = function(){alert(1)}
    }
    
    Demo.prototype.show2 = function(){alert(2)}
    
    var d = new Demo
    d.show1()
    d.show2()
    

    Other Case

    function Demo(){
       this.show1 = function(){alert(1)}
    }
    
    var d = new Demo
    
    Demo.prototype.show2 = function(){alert(2)}
    
    d.show1()
    d.show2()