在JavaScript中访问父类属性

时间:2013-07-03 07:34:24

标签: 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.log(b.x());//5
a.x = 7;
console.log(b.x());//7

1 个答案:

答案 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