2

这是访问父母财产的“好”方式吗?

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
4

1 回答 1

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
于 2013-07-03T07:45:04.467 回答