M.Taki_Eddine
M.Taki_Eddine

Reputation: 160

I can't change a property in a constructor function

I'm a newbie with JavaScript and I'm facing a problem with constructor functions, my problem is that I can't overwrite an old function's property with a new one!

Below is my code:

function myFun() {
  this.anotherFun = function() {
    return true;
  }
}

var myVar = new myFun();

console.log(myVar.anotherFun()); // returns 'true' as expected; 

myFun.prototype.anotherFun = function() {
  return false;
}

console.log(myVar.anotherFun()); // is returns 'true' why not 'false'?

Upvotes: 2

Views: 108

Answers (2)

Angelos Chalaris
Angelos Chalaris

Reputation: 6747

What you are trying to do will not work with your code as own properties will always be looked up before prototype properties, so the change your are making to the prototype property will have no visible effect. In order for this to work, you can change your code to always use prototype properties:

function myFun(){} 
myFun.prototype.anotherFun = function(){return true;}
var myVar=new myFun();
console.log(myVar.anotherFun()); // returns 'true' as expected; 
myFun.prototype.anotherFun=function(){return false;}
console.log(myVar.anotherFun()); // now returns 'false' as expected

If you want to know more about this subject, check out this Question.

Upvotes: 1

Oriol
Oriol

Reputation: 288000

Because when the same property appears multiple times in the prototypical chain, it makes sense to use the closest one.

Your instance has an own property, so you won't be able to override it by adding an inherited one.

You might have not wanted to add myFun as an own property

function myFun(){}
myFun.prototype.anotherFun = function(){return true};
var myVar = new myFun();
console.log(myVar.anotherFun()); // true
myFun.prototype.anotherFun = function(){return false};
console.log(myVar.anotherFun()); // false

Upvotes: 4

Related Questions