从子对象修改原型上的字段
Modifying a field on a prototype from a child object
这是一个清洁的问题。
我使用原型来实现基本的继承,以保持我的代码DRY,我有一些原型,这是为了所有的意图和目的抽象(它不期望它们将被实例化之外被设置为其他对象的原型),他们包含一些代码,"子"对象将调用。问题是原型中的函数依赖于原型的一些字段。更新子对象上的字段显然不会修改原型的字段。我想避免调用
childObject.prototype.field = foo;
,因为继承越深就越混乱。
下面我粘贴了一个例子来解释我要做的事情。你可以看到它在jsfiddle上运行。
//Prints something once.
function Printer(text) {
this.text = text || "";
this.print = function () {
alert(text);
};
}
//Prints everything a set number of times
function AnnoyingPrinter(text, count) {
this.prototype = new Printer(text);
this.count = count || 1;
this.print = function () {
for (var i = 0; i < this.count; i++) {
this.prototype.print();
}
};
}
function doStuff() {
var annoyer = new AnnoyingPrinter("Hello world!", 2);
annoyer.print();
//Now I want to change the text without having to dig down into the prototype (particularly if I ever want to extend AnnoyingPrinter too)
annoyer.text = "Goodbye world!";
annoyer.print();
}
//Expected outcome:
//Hello world!
//Hello world!
//Goodbye world!
//Goodbye world!
//Actual outcome:
//Hello world!
//Hello world!
//Hello world!
//Hello world!
doStuff();
这是原型继承的典型模式。
function Printer(text) {
this.text = text || "";
}
Printer.prototype.print = function() {
alert(this.text);
}
function AnnoyingPrinter(text, count) {
Printer.call(this, text);
this.count = count || 1;
}
AnnoyingPrinter.prototype = Object.create(Printer.prototype);
AnnoyingPrinter.prototype.printAll = function() {
for (var i = 0; i < this.count; i++) {
this.print();
}
}
那么你的doStuff()
可以继续创建一个新的AnnoyingPrinter
,并命名为print()
。
function doStuff() {
var annoyer = new AnnoyingPrinter("Hello world!", 2);
annoyer.printAll(); // "Hello world!" "Hello world!"
annoyer.text = "Goodbye world!";
annoyer.printAll(); // "Goodbye world!" "Goodbye world!"
}
演示: http://jsfiddle.net/DhbgE/
我只需要改变它,使两个构造函数有不同的方法名。如果我们给AnnoyingPrinter
一个.print()
方法,它会遮蔽Printer
的方法。
将属性存储在本地对象中,并在原型函数中引用它们。你不希望在原型对象中保留状态,这应该只用于函数(或者必要时"静态"字段)。
http://jsfiddle.net/C7aPQ/2///Prints something once.
function Printer(text)
{
this.text = text || "";
this.print = function()
{
alert(this.text);
};
}
//Prints everything a set number of times
function AnnoyingPrinter(text,count)
{
this.prototype = new Printer(text);
this.text = text;
this.count = count || 1;
this.print = function()
{
for(var i =0;i<this.count;i++)
{
this.prototype.print.call(this);
}
};
}
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- JavaScript 检查隐藏字段中的值并将其设置为隐藏字段值
- 在wordpress一定时间后更改自定义字段
- 如何在HTML输入字段中添加不可删除的后缀
- Javascript,从原型函数自己的字段中获取“this”
- 使用原型 - 如何观察回车的输入字段
- 如何访问原型上的阴影 JavaScript 对象字段
- 使用原型添加无限的输入字段
- 在 Javascript 中创建子类时,为什么要分配原型字段
- 从子对象修改原型上的字段
- 使用JavaScript原型并访问基类字段
- 为什么实例方法定义在原型中,而实例字段定义在构造函数中?
- 动态控制添加的字段'标签顺序与原型
- 设置原型's对象's字段更改所有实例
- 覆盖公共字段 JavaScript 原型
- 为什么这个原型字段优先于相同的对象字段