原型链、继续 和 instanceof
参考:
MDN:instanceof
MDN:Inheritance and the prototype chain
明白JavaScript的原型链和继续
new完成了什么操纵
new的历程发生了什么?
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');
原型链和prototype属性
原型链是什么
上面的 __proto__
是什么?
就是原型链,原型链是内部 [ [Prototype ]],指向它“父类”的prototype。
翻开浏览器控制台,能够看到函数变量都有一个prototype属性(箭头函数没有)。
经由过程这一句a.__proto__ = A.prototype;
申明a的原型链就是指向函数A的prototype属性。
这里就有一个主要的认识了,虽然名字很像,然则原型链并非prototype属性,同时原型链指向“父类”的prototype。险些一切对象都有原型链(除了null和undefined),经由过程__proto__
能够看到原型链指向什么(固然最好运用 Object.getPrototypeOf 取原型链)
经由过程实验能够发明,js中对象的链能够非常复杂。
一图胜千言。这里借一张图。
简而言之
函数对象,Function,Object,Array等等的原型链都指向Function.prototype
经由过程new操纵符建立的对象原型链指向本来的函数的prototype属性
Object.prototype属性的原型链指向null(到null就住手了)
而Function.prototype(Array,Date,String等等),以及函数对象的prototype,原型链都指向Object.prototype
prototype属性终究是什么呢
能够看到是一个Object,有constructor和原型链。constructor是一个函数,也就是函数本身。这能够为背面提到的继续做准备。
instanceof什么意义
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);
简朴来讲就是如许