如何使用 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/