我写这段代码模拟OOP继承和调用基类中的JavaScript和它的作品:如何使用原型避免在javascript中复制函数?
function Animal(name,age)
{
this._name = name;
this.setName = function (name) { this._name = name }
this.getName = function() { return this._name }
}
function Cat(name,age)
{
Animal.call(this,name,age); // call baseclass constructor
this.getName = function() { return Cat.prototype.getName.call(this)+", a cat" }
}
Cat.prototype = new Animal(); // will create the baseclass structure
/// ***** actual execution *****
var puss = new Cat("Puss",3);
var cheshire = new Cat("Cheshire",10);
// do some actions
console.log (puss.getName());
// change cat's name
puss.setName("Puss in boots");
alert ("new name -->"+puss.getName());
的问题是,对于每个实例“新猫()”中的“的getName”和“的setName”功能被复制。 我已经阅读了很多关于原型设计的文章,但都没有提到调用基类功能的问题。
这是JavaScript的工作原理!每个新创建的对象都具有从原型复制的所有属性。这是正常行为,不是问题。你想要什么? – freakish 2012-04-21 14:52:10