user669677
user669677

Reputation:

Access parent class property in JavaScript

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

Upvotes: 2

Views: 1874

Answers (1)

elclanrs
elclanrs

Reputation: 94101

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

Upvotes: 2

Related Questions