【问题标题】:I can't change a property in a constructor function我无法更改构造函数中的属性
【发布时间】:2016-11-04 05:14:11
【问题描述】:

我是 JavaScript 的新手,我遇到了构造函数的问题,我的问题是我不能用新函数覆盖旧函数的属性!

下面是我的代码:

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'?

【问题讨论】:

  • myFun.prototype.anotherFun= > myFun.anotherFun=
  • 你有两个函数,一个自己的属性和一个原型属性。正如 dandavis 指出的那样,首先查找自己的属性。

标签: javascript constructor properties prototype


【解决方案1】:

因为当同一个属性在原型链中出现多次时,使用最接近的那个是有意义的。

您的实例有自己的属性,因此您无法通过添加继承的属性来覆盖它。

您可能不想将myFun 添加为自己的属性

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

【讨论】:

  • 谢谢,这对我有用!但是我们为什么不写 function myFun(){this.prototype.anotherFun = function(){return true};} 而不是 function myFun(){ } myFun.prototype.anotherFun = function(){return true};
  • @M.Taki_Eddine 因为没有理由在每次创建实例时都运行该代码。所以它应该在构造函数之外。
【解决方案2】:

您尝试执行的操作不适用于您的代码,因为始终会在原型属性之前查找自己的属性,因此您对原型属性所做的更改将没有可见的效果。为了使其工作,您可以更改代码以始终使用原型属性:

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

如果您想了解有关此主题的更多信息,请查看this Question

【讨论】:

  • 谢谢,这对我有用!但是我们为什么不写 function myFun(){this.prototype.anotherFun = function(){return true};} 而不是 function myFun(){ } myFun.prototype.anotherFun = function(){return true}; ——
猜你喜欢
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多