我对Javascript很陌生,我想知道如何修改原型中的公共变量。
function Thing (val)
{
this.x = val;
this.addToX = function (valIn)
{
this.x += valIn;
};
}
function ChildThing ()
{
this.y = 55;
}
ChildThing.prototype = new Thing(10);
var frank = new ChildThing();
console.log("out1: " + frank.x);
frank.addToX(10);
console.log("out2: " + frank.x);此代码在prototype x中取值,即10,并在addToX函数中添加10。新的x值存储在顶层对象中,而不是替换原型中的当前x值。
是否有一种方法可以覆盖原型中现有的x,还是我使用Javascript错误?
发布于 2014-10-01 19:08:19
这要看情况了。改变原型上的x有什么意义?通常,您不希望更改共享属性。但是我想可能有一个用例(生成新的id?)。
至于问题:你可以简单地做:
this.addToX = function(valIn) {
ChildThing.prototype.x += valIn;
};再说一次,我不建议这样做。
编辑您可以通过在将原型设置为原型之前定义它,而无需引用子实例,即
var my_proto = new Thing(10);
ChildThing.prototype = my_proto;然后
this.addToX = function(valIn) {
my_proto.x += valIn;
};或者你甚至可以玩the singleton pattern。
发布于 2014-10-01 20:05:20
你似乎想要的是非常类似的静态成员在古典语言。调用对象实例上的方法并让该方法修改其作用域之外的其他对象的状态是非常误导的。因此,我相信你根本不应该依赖原型来进行这种行为。下面是您可以模拟静态成员的方法。
function SomeClass() {}
SomeClass.staticMember = 'initial value';
SomeClass.changeStaticMember = function (val) { this.staticMember = val; };
SomeClass.changeStaticMember('another value');我相信上面的代码不那么神秘,更善于交流行为。但是,如果您仍然希望通过原型在实例之间共享可变值,您只需避免将属性直接写入原语值,而是将其封装在如下所示的可变共享对象中。注意,整个继承层次结构将共享相同的x值。
//Mutable class to encapsulate the value of X
function XValue(val) {
this.value = val;
}
XValue.prototype = {
constructor: XValue,
valueOf: function () { return this.value; },
set: function (val) { this.value = val; },
add: function (val) { this.value += val; }
};
function Thing(x) {
this.x = x;
}
Thing.prototype = {
constructor: Thing,
_x: new XValue(), //shared mutable object representing the value of X
get x() { return this._x.valueOf(); },
set x(val) { this._x.set(val); },
addToX: function (val) { this._x.add(val); }
};
function ChildThing() {
Thing.call(this, 10); //call parent constructor
}
ChildThing.prototype = Object.create(Thing.prototype);
//helper for snippet
function log(text) {
var span = document.createElement('span');
span.innerHTML = text;
document.body.appendChild(span);
document.body.appendChild(document.createElement('br'));
}
var ct = new ChildThing();
ct.addToX(10);
log('ct.x → ' + ct.x);
log('Thing.prototype.x → ' + Thing.prototype.x);
https://stackoverflow.com/questions/26148691
复制相似问题