proto文件支持继承吗,6To5编译器 - 使用__proto__进行继承

As the output of 6to5 I've got the following code:

var _inherits = function (subClass, superClass) {

if (typeof superClass !== "function" && superClass !== null) {

throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);

}

subClass.prototype = Object.create(superClass && superClass.prototype, {

constructor: {

value: subClass,

enumerable: false,

writable: true,

configurable: true

}

});

// question is about next row

if (superClass) subClass.__proto__ = superClass;

};

_inherits(Controller, CoreController);

Can anybody describe what for used updating __proto__ property? As i try - it doesn't nothing useful

P.S. as documentation says that proto should be object, but in code is used for setting function

解决方案

It's used for 'static" properties inheritance. Please see the code example below:

class Parent {

myMethod() {}

}

console.log(Parent.prototype.myMethod); // [Function]

console.log(Child.prototype.hasOwnProperty('myMethod')); // true

console.log(Parent.myMethod); // undefined

class Child extends Parent {}

console.log(Child.prototype.myMethod); // Function

console.log(Child.prototype.hasOwnProperty('myMethod')); // false

console.log(Child.myMethod); // undefined

Parent.myStaticProp = 42;

console.log(Parent.prototype.myStaticProp); // undefined

console.log(Parent.myStaticProp); // 42

console.log(Parent.hasOwnProperty('myStaticProp')); // true

console.log(Child.prototype.myStaticProp); // undefined

console.log(Child.myStaticProp); // 42

console.log(Child.hasOwnProperty('myStaticProp')); // false

Also, in the similar question on github, yuchi said:

Notice how ‘static’ properties are added after extension.

It’s deprecated because it doesn’t give the interpreter a way to know

beforehand that the object (function, in this case) has a different

prototype chain than the standard one. Every JS interpreter implements

it, and that’s because there’s still no perfect agreement on

Object.setPrototypeOf, in fact for performance reasons IMO.

And looks like that 6to5 wants to be as compatible as possible to ES6

semantics, so setting Child.proto to Parent is an acceptable

tradeoff.

Also, you can look at the good question from basarat about mutating [[Prototype]] and performance by the link:

Why is mutating the [[prototype]] of an object bad for performance?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值