Function.proto === Object.prototype // false
擦,假设失败了呢,让我们来看看为什么不对,Function.proto到底指哪去了
Function.proto === Function.prototype //true
原来指向自己的prototype了呢,那就意味着…
Function instanceof Function //true
yes,然而 Function instanceof Object似乎也能解释了
Function.proto === Function.prototype Function.proto.proto === Object.prototype
所以如果我们让
Function.proto.proto = null Function instanceof Object //false
这回知道为什么不要用 proto 了吧,一不小心重写了会导致所有继承自它的对象都受影响。
为了养成良好的习惯,实际项目最好使用 getPrototypeOf 取原型链,这里只是为了方便我采用proto
一共就分别有两类:
* 原型链指向Function.prototype的函数们
* 原型链指向Object.propotype的对象们
而原型链顶端的Object.prototype就再没有原型链了,所以是空
1 | a.constructor === A.prototype.constructor A.prototype.constructor === A A.prototype.constructor = null a.constructor // => null a instanceof A // true |
这只是函数都有的一个玩意而已, 由于js的函数可以作为构造器,也就是可以 new ,所以所有的 函数的prototype.constructor都指向自己,因此所有的 new 出来的对象也都有一个reference能找到自己的构造器。
下面这个是babel 从es6 class1
class A{
constructor(name) {
this.name= name
}
toString() {
return this.name
}
}
class B extends A {
toString(){ return this.name + 'b' }
}
编译出来的ES5继承1
function _inherits(subClass, superClass) { // 密 }
var A = (function () {
function A(name) {
this.name = name;
}
A.prototype.toString = function toString() {
return this.name;
};
return A;
})();
var B = (function (_A) {
function B() {
if (_A != null) {
_A.apply(this, arguments);
}
}
_inherits(B, _A);
B.prototype.toString = function toString() {
return this.name + 'b';
};
return B;
})(A);