这是访问父母财产的'好'方式吗?
function A(){
this.x = 5;
}
function B(parent){
this.parent = parent;
//this.x = parent.x; this does not work as a reference
}
B.prototype.x = function(){
return this.parent.x;
};
var a = new A();
var b = new B(a);
console.log(b.x());//5
a.x = 7;
console.log(b.x());//7
答案 0 :(得分:2)
不确定这是一个好的模式,你没有做任何继承,每次创建一个新实例时传递父都很麻烦,而x
是一个重复的成员(方法和属性)。以下是您的示例的常见继承模式:
/**
* @class A
*/
var A = (function ClassA(){
function A() {
this.x = 5;
}
return A;
}());
/**
* @class B
* @extends A
*/
var B = (function ClassB(_parent){
function B() {
_parent.call(this); // inherit parent properties
}
B.prototype = Object.create(_parent.prototype); // inherit parent prototype
B.prototype.getX = function(){
return this.x;
};
return B;
}(A));
var a = new A();
var b = new B();
console.log(b.getX()); //= 5
b.x = 7;
console.log(b.getX()); //= 7