[英]how to use prototype to avoid copying of functions in javascript?
我已经编写了这段代码来模拟OOP继承并在javascript中调用baseclass,它的工作原理是:
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() );
问题是,对于“ new Cat()”的每个实例,“ getName”和“ setName”函数都被复制。 我已经阅读了很多关于原型的文章,但是都没有解决调用基类函数的问题。
您应该将方法分配给函数的原型,例如,
function Animal(name, age) {
this._name = name;
this._age = age;
}
Animal.prototype.getName = function () { return this._name; }
Animal.prototype.setName = function (value) { this._name = value; }
function Cat(name, age) {
Animal.call(this, name, age);
}
Cat.prototype = new Animal();
Cat.prototype.getName = function () {
return Animal.prototype.getName.call(this) + ", a cat";
}
来自http://phrogz.net/js/classes/OOPinJS2.html
Javascript没有任何指向其父类的'super'属性。 而是使用Function对象的call()方法,该方法允许您使用其他对象作为其上下文来运行函数。 如果您需要将参数传递给此函数,则它们将放在“ this”之后。
在您的情况下,它与“方法”的功能相同,因此您可以执行以下操作:
Animal.prototype.setName.call(this, name);
您是否正在寻找存储原型数据的__proto__
? https://developer.mozilla.org/zh-CN/JavaScript/Reference/Global_Objects/Object/Proto
如果您执行console.log(puss.__proto__.getName)
您将获得似乎是“基类”功能的功能,但是我不确定这是如何跨浏览器的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.