你想讓一個實例繼承另一個實例的私有狀態嗎?當然你可以在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) {
// constructor code
} 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;
}());
現在210
您可以創建一個奇瓦瓦如下:
var chi = new Chihuahua;
alert(chi.saySize()); // I am a small dog.
alert(chi.size); // undefined
觀看演示:http://jsfiddle.net/b3Eyn/
注:我寫這個答案只是爲了表明它可能在JavaScript中繼承私有狀態。不過,我會建議你不要使用這種模式。如果你設計好你的代碼,那麼你就不需要首先繼承私有狀態。
這是什麼功能狗=(函數(){})()'? – Amberlamps
只有在_any_語言中定義了'private'成員才能支持OOP。我沒有得到你想要做的。 – Leri
一般來說不,但是你的「私人功能」很容易通過'notSoPrivateSaySize = new Dog()來訪問。publicSaySize();' – Bergi