【问题标题】:javascript Inheriting properties from another functionjavascript从另一个函数继承属性
【发布时间】:2013-08-06 12:06:13
【问题描述】:

这是一个我无法解决的问题。我有一个名为 Person 的对象。我添加了一个名为 changeCol(el, col) 的方法,它需要两个参数,一个是对元素的引用,另一个是颜色属性。所以当我们调用这个方法时,这将改变元素的颜色。现在我将一个新方法附加到名为 changeSize(size); 的对象上。它需要一个称为(大小)的参数。现在的疑问是我什么时候会调用第二个方法给一个元素,我也想改变颜色并增加字体大小。

在第一种方法中,我引用了元素并更改了颜色。所以,同样的事情我不想在第二种方法中重复。那么,如何将第一个方法的参数继承给第二个方法。

这是到目前为止的代码 -

function Person(){

}
Person.prototype.changeCol = function(el, col){
  var elem = document.getElementById(el);
  elem.style.color = col;
};

Person.prototype.changeSize = function(size){

};



//here we are calling the method
var foo = new Person();
foo.changeCol('paragraph', 'blue');// this is working fine.
foo.changeSize('45px'); // this method will change the size and color as well.

【问题讨论】:

  • changeSize() 方法是否会在某个时候独立于changeCol() 函数调用,或者它们总是一起调用?
  • changeCol()Person 原型没有任何作用时,它有什么意义呢?
  • 我想单独调用 changeSize() 方法。但它也会改变颜色。所以可能 changeCOlor 方法会在 changeSize 方法中执行。
  • 但是改变颜色需要参数:这些值是从哪里来的?

标签: javascript oop object inheritance


【解决方案1】:

您可以在创建人员时使用this.elem 设置elem 或检查是否设置了elem。

function Person(elemID){
  // could set the elem here
  this.elem=false;
}
Person.prototype.changeCol = function(el, col){
  this.elem = this.elem || document.getElementById(el);
  this.elem.style.color = col;
};
Person.prototype.changeSize = function(size){
  this.elem = this.elem || document.getElementById(el);
  ...
};

【讨论】:

  • 调用 changeSize() 时颜色会发生什么?此解决方案对此无济于事。
【解决方案2】:

也许我在这里遗漏了一些东西,但我不明白你期望它如何工作。

 var person1 = new Person();
 person1.setSize("45px");   // what should color be set to?

 var person2 = new Person();
 person2.changeColor("p1", green);

 var person3 = new Person();
 person3.setSize("45px");   // what us your intention now?

函数根本不会相互继承。如果要为所有实例的 el 和 color 设置默认值,请将它们设置为原型属性。

【讨论】:

  • 好的,这里有疑问。在您调用 changeColor() 的 person2 对象中,它会更改颜色。但我想要的是在 person1 对象中,当我们调用 setSize(size); 时,这个方法也会改变字体大小和颜色。
  • 对,但是我们如何知道第 1 个人的预期颜色呢?我们还没有为任何东西设置任何颜色。我不相信你有一个明确的要求。我在上面的例子中有两个明确的问题,告诉我你想要什么行为
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多