2

Is this a 'good' way of accessing parent's property?

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
Alexandre Neukirchen
  • 2,713
  • 7
  • 26
  • 36
  • Here is how you can do it with constructor functions but set inheritance with a helper function (not Object.create as it doesn't work in IE8) and adding a superClass_ object to your "child" constructor to be used when overriding "parent" methods http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Jul 03 '13 at 09:31

1 Answers1

2

Not sure that's a good pattern, you're not doing any inheritance, passing the parent everytime you create a new instance is cumbersome, plus x is a duplicated member (both a method and a property). Here's a common inheritance pattern with your example:

/**
 * @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
elclanrs
  • 92,861
  • 21
  • 134
  • 171