-2

Have a look at code below:

function person() {
  this.fname = 'baby';
  this.lname = 'boy';
  this.walk = function () {
    return 'i can walk';
  }
}
person.prototype.walk=function(){ return 'all can walk';}


var obj=new person();

obj.walk();

Now i want to let both these funtions in my code but want that when i make the call to walk using obj.walk()...it should be calling walk function from prototype,as result return me 'all can walk'

Optimus
  • 116
  • 1
  • 7
  • 1
    If you want to do that, why are you adding that "walk" property in the constructor? What is it that you're trying to achieve? – Pointy Apr 29 '15 at 14:30
  • Here's a similar question that has already been answered that might help: http://stackoverflow.com/questions/12183011/javascript-redefine-and-override-existing-function-body – jcmiller11 Apr 29 '15 at 14:37
  • Why -2 for this question...Because either it is not possible directly which is not indeed as depicted by first answer...So can you pls remocve -2 for this question?? – Optimus Apr 30 '15 at 18:12

3 Answers3

1

You can delete obj.walk to remove the property only for that specific object, and force it to use the inherited method.

function person() {
  this.fname = 'baby';
  this.lname = 'boy';
  this.walk = function () {
    return 'i can walk';
  }
}
person.prototype.walk=function(){ return 'all can walk';}


var obj=new person();

delete obj.walk;

console.log(obj.walk());
Scimonster
  • 32,893
  • 9
  • 77
  • 89
1

Here's a way to do it, but I believe it requires ES5.

function person() {
  this.fname = 'baby';
  this.lname = 'boy';
  this.walk = function () {
    return 'i can walk';
  }
}
person.prototype.walk=function(){ return 'all can walk';}


var obj=new person();

obj.walk();

//to call the prototype's function
Object.getPrototypeOf(obj).walk.call(obj);
Michael B.
  • 331
  • 1
  • 5
0

This behavior - that when you invoke foo.bar(), it first checks if "foo" has a method named "bar", and THEN checks the prototype only if it doesn't find one - is a pretty central part of JS, and really not something that can be changed.

If you have both an instance and a prototype method, the instance method will shadow the prototype method.

Retsam
  • 30,909
  • 11
  • 68
  • 90