事变的原由是在问答上看到一个朋侪的发问,问的是阮一峰先生 ECMAScript 6 入门 上关于super关键字的一段代码题目,下面是这个代码的截图:
这位楼主说他以为 this.x
的值不是3,下面有网友说把代码粘贴到 chrome 控制台一试就是这效果没错,厥后楼主说是他想错了。我也顺便把代码粘贴到 chome 下实行后答案也确实是3。
原本这个事没啥就完毕了,恰好我开着 WebStorm 预备写代码,随手粘贴到代码文件内里,保留 > webpack打包 > 革新浏览器,瞅了一眼 Console:
!这是神马状况,输出竟然是2!
题目剖析
为啥与 chrome 直接运转的效果不一致呢?想了想题目应当出在 Babel 转码上。立时翻开转码后的文件,定位到这段代码的位置:
var B = function (_A) {
_inherits(B, _A);
function B() {
_classCallCheck(this, B);
var _this = _possibleConstructorReturn(this, (B.__proto__ || Object.getPrototypeOf(B)).call(this));
_this.x = 2;
_set(B.prototype.__proto__ || Object.getPrototypeOf(B.prototype), 'x', 3, _this);
console.log(_get(B.prototype.__proto__ || Object.getPrototypeOf(B.prototype), 'x', _this)); // undefined
console.log(_this.x); // 3
return _this;
}
return B;
}(A);
super.x = 3;
对应的是 _set(B.prototype.__proto__ || Object.getPrototypeOf(B.prototype), 'x', 3, _this);
这里有个 _set()
函数,再看下这个 _set()
是啥:
var _set = function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
set(parent, property, value, receiver);
}
} else if ('value' in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
setter.call(receiver, value);
}
}
return value;
};
细致看看这个函数后,邃晓是怎样回事了。连系阮一峰先生的代码和上面的转码能够看出,_set()
传进来的第一个参数是 B.prototype.__proto__
— 也就是A的原型对象 — A.prototype
,第一句代码会先找 x属性
的描述符,假如找不到继承顺着原型链找… 当然是找不到的了,所以相当于啥也没实行,this.x
的值依然是2。
假如根据这个 _set()
函数的逻辑,在什么状况下 this.x
的值才会是3呢?要满足两个前提:
-
A.prototype
上必须有x
属性定义 - 这个
x
属性定义上还必须定义set
接见器
比如像下面如许:
Object.defineProperty(A.prototype, 'x', {
get: function () {
return this._x;
},
set: function (value) {
this._x = value;
}
});
然后再跑一把,果真 this.x
的值是3了!等一下… 怎样 console.log(super.x); // undefined
这句的效果不是 undefined 也是3了呢?看下转码那边另有个 _get()
函数:
var _get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
好吧,代码走到末了 else 的 getter
那边了,天然 super.x
的读取效果就是3了
现在还没时候看为啥 Babel 要这么转码处置惩罚,假如你有答案了迎接留言议论。