Javascript ECMAScript 6中的原型链
我最近看到Axel Rauschmayer博士的这篇文章: 以下片段从ECMAScript 5的角度大致描述了ECMAScript 6原型链是如何工作的(原文第4.2节): ECMAScript 5中的“引擎盖下”视图:Javascript ECMAScript 6中的原型链,javascript,subclass,ecmascript-6,ecmascript-harmony,Javascript,Subclass,Ecmascript 6,Ecmascript Harmony,我最近看到Axel Rauschmayer博士的这篇文章: 以下片段从ECMAScript 5的角度大致描述了ECMAScript 6原型链是如何工作的(原文第4.2节): ECMAScript 5中的“引擎盖下”视图: // ECMAScript 5 // Instance is allocated here function Point(x, y) { // Performed before entering this constructor: this = Objec
// ECMAScript 5
// Instance is allocated here
function Point(x, y) {
// Performed before entering this constructor:
this = Object.create(new.target.prototype);
this.x = x;
this.y = y;
}
···
function ColorPoint(x, y, color) {
// Performed before entering this constructor:
this = uninitialized;
this = Reflect.construct(Point, [x, y], new.target); // (A)
// super(x, y);
this.color = color;
}
Object.setPrototypeOf(ColorPoint, Point);
···
let cp = Reflect.construct( // (B)
ColorPoint, [25, 8, 'green'],
ColorPoint);
// let cp = new ColorPoint(25, 8, 'green');
在上述代码中,我理解这是有效的:
Object.getPrototypeOf(ColorPoint) === Point //true
因此:
Object.setPrototypeOf(ColorPoint, Point);
我很难理解为什么这也是事实,因为我找不到任何“ES5”解释:
Object.getPrototypeOf(ColorPoint.prototype) === Point.prototype // true
也许像这样的一行不见了
Object.setPrototypeOf(ColorPoint.prototype, Point.prototype);
提前感谢大家。从ES5角度看,“引擎盖下视图”不包括这些行-它隐藏在…
部分中。这段代码的要点是解释与ES5继承的区别,它们都是关于this
初始化、new.target
、super
行为以及继承自其他构造函数的构造函数函数
原型的基本ES5继承仍然存在,并且像往常一样工作:
ColorPoint.prototype = Object.create(Point.prototype, {
constructor: {value:ColorPoint, writable:true, enumerable:false, configurable:true}
});
// ... further method definitions
其效果与使用
Object.setPrototypeOf(…)
相同,后者指定内部[[Prototype]]]
属性。引擎只需直接修改该属性,而无需使用setPrototypeOf()
表示JavaScript中的步骤。ES6不在引擎盖下使用setPrototypeOf
,它只是为标准化不推荐的,非标准的\uuuu proto\uuuu
功能,出于性能原因,不鼓励使用该功能。仅供参考,Object.setPrototypeOf(ColorPoint,Point)
负责继承静态方法。我猜你的意思是ColorPoint.prototype
。另外,你能告诉我为什么构造函数的属性值设置为点
,而没有恢复为色点
?@Konos5:Ooops,当然。非常细心,谢谢!很公平。你能告诉我这个密码是在哪里发生的吗?一旦遇到extends
,是否可以自动调用它?是的,一旦遇到extends
,就会立即执行对象.create(Point.prototype)
,但是当遇到类的constructor(){…}
方法时,ColorPoint
函数实例化和.prototype
赋值和.constructor
属性创建就开始了。但实际上顺序在这里并不重要(显然ES5不足以准确地描述所有细节). ES6中的操作顺序只有在流程中出现错误时才起作用。
ColorPoint.prototype = Object.create(Point.prototype, {
constructor: {value:ColorPoint, writable:true, enumerable:false, configurable:true}
});
// ... further method definitions