参考:
MDN:instanceof
MDN:Inheritance and the prototype chain
理解JavaScript的原型链和继承javascript
new的过程发生了什么?html
function A(name){ this.name = name } var a = new A('hehe') // var a = new A('hehe') => var a = new Object(); a.__proto__ = A.prototype; A.call(a, 'hehe');
上面的 __proto__
是什么?
就是原型链,原型链是内部 [ [Prototype ]],指向它“父类”的prototype。java
打开浏览器控制台,能够看到函数变量都有一个prototype属性(箭头函数没有)。
经过这一句a.__proto__ = A.prototype;
说明a的原型链就是指向函数A的prototype属性。浏览器
这里就有一个重要的认识了,虽然名字很像,可是原型链并非prototype属性,同时原型链指向“父类”的prototype。几乎全部对象都有原型链(除了null和undefined),经过__proto__
能够看到原型链指向什么(固然最好使用 Object.getPrototypeOf 取原型链)babel
经过实验能够发现,js中对象的链能够很是复杂。
一图胜千言。这里借一张图。app
简而言之函数
函数对象,Function,Object,Array等等的原型链都指向Function.prototype网站
经过new操做符建立的对象原型链指向原来的函数的prototype属性this
Object.prototype属性的原型链指向null(到null就中止了)spa
而Function.prototype(Array,Date,String等等),以及函数对象的prototype,原型链都指向Object.prototype
能够看到是一个Object,有constructor和原型链。constructor是一个函数,也就是函数自身。这能够为后面提到的继承作准备。
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
Syntax:
object instanceof constructor
意思就是object.__proto__===constructor.prototype
MDN的教程中举例
// defining constructors function C() {} var o = new C(); // true, because: Object.getPrototypeOf(o) === C.prototype o instanceof C;
可是
var simpleStr = 'This is a simple string'; var myString = new String(); simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
但是在浏览器中试验Object.getPrototypeOf(simpleStr) === String.prototype
结果是true,大概这算做一个特殊状况
https://babeljs.io/repl/
能够在这个网站在线编译并查看结果
class A{ constructor(name) { this.name= name } toString() { return this.name } } class B extends A { toString(){ return this.name + 'b' } }
编译出来的ES5继承
function _inherits(subClass, superClass) { subClass.prototype.__proto__=superClass.prototype; } 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);
简单来讲就是这样