访问JavaScript中的父类属性
这是访问家长财产的“好”方式吗访问JavaScript中的父类属性,javascript,class,Javascript,Class,这是访问家长财产的“好”方式吗 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.lo
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
不确定这是否是一个好的模式,您没有进行任何继承,每次创建新实例时传递父级都很麻烦,而且
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
下面是如何使用构造函数,但使用辅助函数(不是Object.create,因为它在IE8中不起作用)设置继承,并将超类对象添加到“子”构造函数中,以便在重写我已经测试过的“父”方法时使用,而这也不能作为我的注释部分使用。