如何在不使用JavaScript ES6中的构造函数的情况下使用对象文字来创建类的实例?

问题描述 投票:6回答:2

我正在尝试学习JavaScript ES6,这是一种非常酷的语言,我认为我应该练习一下,但我无法制作an exercise。那么我如何使用object literal复制一个类。

例如,该类是:

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

我想在这里使用object literal做一些事情来使输出成为真。

var fakePoint = YOUR_CODE_HERE
console.log(fakePoint instanceof Point)
javascript oop ecmascript-6
2个回答
5
投票

我猜这个练习正在寻找一个使用__proto__ as an object literal key的解决方案 - 如mentioned in the slides

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

但是,__proto__ is deprecated(在对象文字和Object.prototype getter / setter中)并且仅在Web浏览器中作为ES6标准化遗留功能提供,因此我建议避免使用此类代码。正确的解决方案是使用Object.create

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

0
投票

只是为了好玩,这是另一种方法,可能不是练习作者想要的,但可以说是一个对象文字:

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一个custom hasInstance implementation,它不检查原型链,而是检查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
};
© www.soinside.com 2019 - 2024. All rights reserved.