javascript - 如何使用 ES5 原型(prototype)重构类表达式?

标签 javascript es6-class

如何使用 ES5 原型(prototype)语法重构类表达式?

我正在尝试使用类表达式扩展 native 类。此代码工作正常,但扩展 native 类是 not supported by babel我希望将来将我的代码转换为 ES5。

这是摘自 google's custom elements primer 的代码.

customElements.define('bigger-img', class extends Image {
    // Give img default size if users don't specify.
    constructor(width = 50, height = 50) {
        super(width * 10, height * 10);
    }
}, { extends: 'img' });

所以问题很简单:

如何使用 ES5 兼容的东西重构 ES2015 类表达式(或者只是 babel 兼容,但这个问题与 babel 并不真正相关)。

你能简单解释一下或者给我引用一下解释 ES6 类如何与原型(prototype)一起工作的吗?

最佳答案

ES5 中的类扩展有点棘手。您需要使用原型(prototype)链来完成此任务。为此,您需要知道原型(prototype)的作用。

给定以下函数:

function BaseClass(){
}

您可以向其原型(prototype)添加属性:

BaseClass.prototype.doSomething();

创建该类的实例时,您可以在创建的对象上调用该函数:

var baseObj = new BaseClass();
baseObj.doSomething();

这是可行的,因为有一个名为 __proto__ 的属性,它由生成函数的 prototype 确定(此处:BaseClass)。

如果您访问对象上不直接存在的属性,解释器现在开始查找原型(prototype)链(检查 obj.__proto__ 是否具有此属性)。

如果你想扩展BaseClass怎么办?对于扩展,您需要做两件事:

  • 调用基类的构造函数

  • 将原型(prototype)添加到原型(prototype)链

function DerivedClass(){
    BaseClass.call(this);
}
DerivedClass.prototype.__proto__ = BaseClass.prototype; // That's what happens
DerivedClass.prototype = Object.create( BaseClass.prototype ); // That's how you should do it

生成器函数的 prototype 成为其生成对象的 __proto__ 属性。

https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes

这里说,新语法只是完成我上面解释的内容的一种更舒适的方式。在内部它应该做或多或少完全相同的事情。

正如评论中所指出的,您永远不应该手动分配__proto__,而应使用Object.create(prototypeObject)

关于javascript - 如何使用 ES5 原型(prototype)重构类表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42616468/

相关文章:

javascript - PHP if 语句中的 Jquery

javascript - webpack build less files 输出一个 css minify 文件

javascript - Javascript ES6 类应该用作 React State 吗?

javascript - 如何在 Javascript 中调用同一个类中的另一个方法

javascript - 所有浏览器都支持文件大小验证代码

javascript - 为什么输入类型=文件的变化没有被识别为 `form.serialzie()`

javascript - 为什么 String 类会从 Function.prototype 扩充?

javascript - 未捕获的类型错误 : Cannot read property 'props' of null in React Class

javascript - ES6 : Can't Deconstruct inside a call constructor

javascript - 调用 Javascript 类方法时出现错误 'Can' t find variable'