【问题标题】:JavaScript ES6 prototype functionJavaScript ES6 原型函数
【发布时间】:2018-05-25 04:00:19
【问题描述】:

我想让getArea() 函数成为原型,但不确定这种 ES6 (?) 格式是否会自动为我执行此操作,或者我是否仍需要在单独的 Object.prototype.method = function() {} 中声明原型 构造?

class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    getArea() {
        return this.height * this.width;
    }
}

【问题讨论】:

标签: javascript methods prototype


【解决方案1】:

是的。

ES6 类格式基本上翻译成这样:

function Polygon(height, width) {
  this.height = height;
  this.width = width;
}

Polygon.prototype.getArea = function() {
    return this.height * this.width;
};

【讨论】:

  • 进一步确认 - 我刚刚使用 TypeScript 和 Babel 编译了问题中的代码,这几乎就是得到输出的代码。
  • 一个重要的区别是该方法是不可枚举的。
  • 我不确定 ES6 或 ES5 语法在这方面会有什么不同。
  • 您使用的 ES5 语法使得getArea 在枚举实例的属性时会出现。 for (var x in new Polygon()) { console.log(x) }。但是在 ES6 中,因为它是不可枚举的,getArea 不会出现在循环中。要在 ES5 浏览器中获得这种行为,您可以使用 Object.defineProperty 将方法添加到原型中。
  • 啊,好点子。我不认为我自己意识到了这一点。刚刚自己测试过,确实是这样。
猜你喜欢
  • 2019-02-03
  • 2023-02-10
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
相关资源
最近更新 更多