0

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 
Prem
  • 5,685
  • 15
  • 52
  • 95
  • 1
    [Here's another question which might provide some insight and possible alternatives](https://stackoverflow.com/questions/13040684/javascript-inheritance-object-create-vs-new) – kingdaro Apr 30 '18 at 03:40
  • 2
    Possible duplicate of [JavaScript inheritance: Object.create vs new](https://stackoverflow.com/questions/13040684/javascript-inheritance-object-create-vs-new) – Alexis King Apr 30 '18 at 03:43
  • Your question title is asking about inheritance, but your question body is about making an instance. These are two different things. – Mark Apr 30 '18 at 03:43
  • @Mark_M Don't we make instance to inherit from parent objects? – Prem Apr 30 '18 at 03:46

2 Answers2

2

To create an instance of a constructor, use new

var rectangle = new Shape()
Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91
0

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
brk
  • 48,835
  • 10
  • 56
  • 78