你希望一个实例可以继承另一个实例的私有状态?在 JavaScript 中,当然可以做到。首先,我们需要定义一个实用函数:
function weakBind(functable, prototype, state) {
return function () {
return functable.apply(this, Object.getPrototypeOf(this) === prototype ?
[state].concat(Array.prototype.slice.call(arguments)) : arguments);
};
}
现在我们可以创建基类如下所示:
var Dog = (function () {
function Dog() {
if (this instanceof Dog) {
} else return Object.create(private);
}
var public = Dog.prototype, private = Object.create(public, {
size: {
value: "big"
}
});
public.saySize = weakBind(function (private) {
return "I am a " + private.size + " dog.";
}, public, private);
return Dog;
}());
现在你可以按照以下步骤创建一只狗:
var dog = new Dog;
alert(dog.saySize()); // I am a big dog.
alert(dog.size); // undefined
我们可以按以下方式继承私有状态:
var Chihuahua = (function () {
function Chihuahua() {
Dog.call(this);
}
var private = Dog();
Object.defineProperty(private, {
size: {
value: "small"
}
});
var public = Chihuahua.prototype = Object.create(Dog.prototype);
public.saySize = weakBind(public.saySize, public, private);
return Chihuahua;
}());
现在您可以按照以下步骤创建一只吉娃娃:
var chi = new Chihuahua;
alert(chi.saySize()); // I am a small dog.
alert(chi.size); // undefined
查看演示:http://jsfiddle.net/b3Eyn/
注意:我写这篇答案只是为了展示在JavaScript中继承私有状态是可能的。但是我建议你不要使用这种模式。如果你设计你的代码得当,那么你就不需要在第一时间继承私有状态。
function Dog = (function() {})()
是什么? - Amberlampsprivate
成员在任何支持面向对象编程的语言中,仅在定义它们的类内部可见。我不明白你试图做什么。 - Leri