Prem
Prem

Reputation: 5987

How to inherit using Object.create()

I created an instance of Shape using Object.create() method and tried accessing the property of Shape as follows, but the inherited property becomes undefined:

    function Shape(){
      this.x = 10;
      this.y = 20;
    }

    var rectangle = Object.create(Shape);

    console.log(rectangle.x) // undefined 

Upvotes: 0

Views: 39

Answers (2)

brk
brk

Reputation: 50291

May declare the shape as an object instead of function though functions are first class object in js. Create a function inside this object and return the required value from this function

var shape = {
  userProperty: function(x, y) {
    this.x = x || 10; // if no value of x is passed it will be 10
    this.y = y || 10; // if no value of y is passed it will be 10
    return {
      x: this.x,
      y: this.y
    }
  }
}
var rectangle = Object.create(shape);
console.log(rectangle.userProperty(40).x) // 40

Upvotes: 0

Sebastian Olsen
Sebastian Olsen

Reputation: 10878

To create an instance of a constructor, use new

var rectangle = new Shape()

Upvotes: 2

Related Questions