Javascript 利用父对象中的私有变量实现原型继承
我试图在父对象中存在私有变量时实现原型继承 考虑这样一个代码:Javascript 利用父对象中的私有变量实现原型继承,javascript,prototype,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 () {
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());
但是,父对象上不存在私有变量isLive,并且只存在公共变量,那么继承可以很容易地实现这一点。,
就像这个链接一样
那么,当父对象中存在私有变量时,如何实现相同的原型继承。设置继承的方式是错误的。对
函数原型的赋值应在构造函数之外。然后,如果将父构造函数应用于新的“子”对象,它也将为其分配闭包
例如:
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;
}
查看一下,了解一下为什么对象。创建更好地设置继承
试图创建访问“私有属性”的原型函数毫无意义。只有构造函数中定义的闭包才能访问这些变量。设置继承的方式是错误的。对函数原型的赋值应在构造函数之外。然后,如果将父构造函数应用于新的“子”对象,它也将为其分配闭包
例如:
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;
}
查看一下,了解一下为什么对象。创建更好地设置继承
试图创建访问“私有属性”的原型函数毫无意义。只有构造函数中定义的闭包才能访问这些变量