Search code examples
javascriptprototype

Method not override in java script prototype



I just reading java script prototype programming, just tried one small code.

function Ninja(){
  this.swingSword = function(){
    return true;
  };
}

//override the prev one
Ninja.prototype.swingSword = function(){
  return false;
};

var ninja = new Ninja();
console(ninja.swingSword());

but I thought the OP of this will be false, unfortunately it has given output as true, my second method is not overriding first one. why?


only Ninja.prototype.swingSword() JsFiddle this give correct override .....

So what is the purpose creating object(ninja) here ?


Solution

  • Defining a function on a prototype extends that function to all its instances.

    When you call the function it will always look at the instance itself first. If it doesn't find the function on the instance, then it looks at the prototype.

    Since you are essentially overriding the prototype swingSword by creating a swingSword function directly in your Ninja constructor, which ensures that every instance of Ninja will already have a swingSword function, it never bothers looking for it on the prototype.