How can I use an object literal to instantiate a class without using a constructor in JavaScript ES6?

I am trying to learn JavaScript ES6, which is a very cool language, and I thought I needed a little practice, but I can’t do the exercise . So how can I use an object literal to copy a class.

For example, the class:

class Point {
  constructor(x, y) {
    this.x = x, this.y = y
  }
  add(other) {
    return new Point(this.x + other.x, this.y + other.y)
  }
}

And I want to do something here using the object literal to make the conclusion true.

var fakePoint = YOUR_CODE_HERE
console.log(fakePoint instanceof Point)
+6
source share
2 answers

, , __proto__ - :

var fakePoint = {
    __proto__: Point.prototype,
    x: Math.random(),
    y: Math.random()
};
console.log(fakePoint instanceof Point)

__proto__ ( , Object.prototype getter/setter) - ES6 , . - Object.create:

var fakePoint = Object.assign(Object.create(Point.prototype), {
    x: Math.random(),
    y: Math.random()
});
console.log(fakePoint instanceof Point)
+5

, , , , , , , , :

var fakePoint = {
  x: Math.random(),
  y: Math.random(),
  fakeConstructor: Object.defineProperty(Point, Symbol.hasInstance, {
    value(o) { return o.fakeConstructor == this; }
  })
};
console.log(fakePoint instanceof Point)

, Point a custom hasInstance , , fakeConstructor . "x" in o && "y" in o - . , , ,

Object.defineProperty(Point, Symbol.hasInstance, {
  value(o) { return o.fakeConstructor == this; /* this === Point */ }
});
var fakePoint = {
  x: Math.random(),
  y: Math.random(),
  fakeConstructor: Point
};
0

All Articles