Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding prototype property or function

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

// Should return false, but will be overridden
Ninja.prototype.swingSword = function(){
  return false;
};

var ninja = new Ninja();
log( ninja.swingSword(), "Calling the instance method, not the prototype method." );

now log showing me true. which means swingSword that were defined in Ninja.prototype has overridden so how can i override the constructor function or property.?? i know that preference is given to constructor variable then why need to define a function or property inside prototype??

like image 429
Mohammad Faizan khan Avatar asked Feb 27 '14 06:02

Mohammad Faizan khan


People also ask

Can we override prototype in JavaScript?

Prototyping allows objects to inherit, override, and extend functionality provided by other objects in a similar manner as inheritance, overriding, abstraction, and related technologies do in C#, Java, and other languages. Every object you create in JavaScript has a prototype property by default that can be accessed.

Do all functions have a prototype property?

Note: Not all Function objects have the prototype property — see description.

What is the difference between __ proto __ and prototype?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.

How many properties does a prototype object have?

prototype by default has one own property: constructor , which references the constructor function itself — that is, Box. prototype. constructor === Box . This allows one to access the original constructor from any instance.


2 Answers

The reason to define a function on the prototype is so that it is shared between all instances. This will save you some memory rather than each instance having its own copy of a function defined in the constructor.

Some other references you might be interested in:

Javascript when to use prototypes

http://javascript.crockford.com/inheritance.html

like image 112
Stephen Kaiser Avatar answered Oct 17 '22 00:10

Stephen Kaiser


This is by design. Do not set the value in the constructor if you want it to return false.

You can also make a setter method:

function Ninja() {
    var swordState = true;
    this.swingSword = function () {
        return swordState;
    };
    this.setSword = function (b) {
        swordState = b;
    };
}

// Should return false, but will be overridden
Ninja.prototype.swingSword = function () {
    return false;
};

var ninja = new Ninja();
console.log(ninja.swingSword(), "Calling the instance method, not the prototype method.");
ninja.setSword(false);
console.log(ninja.swingSword()); // returns false
like image 27
Andrew Templeton Avatar answered Oct 17 '22 01:10

Andrew Templeton