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 に答える