Mut*_*han 0 javascript prototype
当父对象中存在私有变量时,我试图实现原型继承.
考虑像这样的代码,
function Piece(isLiveArg) {
var isLive = isLiveArg; // I dont wish to make this field as public. I want it to be private.
this.isLive = function(){ return isLive;}
}
Piece.prototype.isLive = function () { return this.isLive(); }
function Pawn(isLiveArg) {
// Overriding takes place by below assignment, and getPoints got vanished after this assignment.
Pawn.prototype = new Piece(isLiveArg);
}
Pawn.prototype.getPoints = function(){
return 1;
}
var p = new Pawn(true);
console.log("Pawn live status : " + p.isLive());
Run Code Online (Sandbox Code Playgroud)
但是,isLive 父对象上不存在私有变量,只存在公共变量,然后继承可以很容易地实现这一点.就像在这个链接中一样,http://jsfiddle.net/tCTGD/3/.
那么,当父对象中存在私有变量时,我将如何实现相同的原型继承.
你设置继承的方式是错误的.赋值Func.prototype应该在构造函数之外.然后,如果将父构造函数应用于新的"子"对象,它也将为其分配闭包.
例:
function Piece(isLiveArg) {
var isLive = isLiveArg;
this.isLive = function(){ return isLive;}
}
function Pawn(isLiveArg) {
// apply parent constructor
Piece.call(this, isLiveArg);
}
// set up inheritance
Pawn.prototype = Object.create(Piece.prototype);
Pawn.prototype.constructor = Pawn;
Pawn.prototype.getPoints = function(){
return 1;
}
Run Code Online (Sandbox Code Playgroud)
看看使用`Object.create`进行继承的好处,可以了解为什么Object.create更好地设置继承.
尝试创建访问"私有属性"的原型函数是没有意义的.只有构造函数中定义的闭包才能访问这些变量.