如果类只是原型上的语法糖,我会如何
应该脱糖吗?
例如这是一个好文章 https://www.sitepoint.com/understanding-ecmascript-6-class-inheritance/就此事。所以如果你创建了一个实体Animal
using class
:
class AnimalES6 {
constructor(name) {
this.name = name;
}
doSomething() {
console.log("I'm a " + this.name);
}
}
var lionES6 = new AnimalES6("Lion");
lionES6.doSomething();
原型版本看起来像这样:
var Animal = (function () {
function Animal(name) {
this.name = name;
}
// Methods
Animal.prototype.doSomething = function () {
console.log("I'm a " + this.name);
};
return Animal;
})();
var lion = new Animal("Lion");
lion.doSomething();
更复杂的是extend
功能(例如继承的 TypeScript 模拟):
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
您可以向我展示创建 React 元素的不同方法吗
有类和原型(即没有类和 React.createClass)?
这个问题还有一些已经回答的问题,例如this one https://stackoverflow.com/questions/40366024/how-to-implement-normal-es5-prototypal-inheritance-in-react.
但在我看来,真正的问题仍然是:你想要_____吗?
既然您链接了 Eric Elliot 的文章,您可能会注意到围绕 EC6 存在一种争议class
JavaScript 世界中的 es。除了您发布的示例之外,还有更多开发人员的一些意见汇总,例如这个 github 仓库 https://github.com/joshburgess/not-awesome-es6-classes/, here https://www.quora.com/Are-ES6-classes-bad-for-JavaScript和更多。也有文章捍卫其目的class
...
无论如何,React 的创造者似乎已经接受了它的“邪恶”class
正如您所指出的,当您尝试在 React 中使用原型方法时,您会遇到问题。所以我认为:为什么要费心呢?我也更喜欢 javascript 的原型性质,也喜欢 ReactJS 框架,但在我看来,最好提出一些结合了两者优点的新框架,比如“Protypal React”,而不是试图强制原型化当 React 不打算用于此类用途时。
但类不主要是关于继承吗?
这可能在评论中得到了回答,但没有。类有其优点Composition
设计理念重于继承。它取决于需求 https://en.wikipedia.org/wiki/Composition_over_inheritance但是许多框架/库都建立在面向对象的语言之上,这些语言使用类包含组合而不是继承,例如统一。
不管怎样,这是一个很好的问题,我也想分享我对此事的想法。希望它能帮助您形成意见。