多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[toc] #div1.__proto__ -> HTMLDivElement.prototype->HTMLElement.prototype->Element.prototype->Node.prototype->EventTarget.prototype->Object.prototype ## 原型链继承(最常用) 原型继承是我们JS中最常用的一种继承方式 子类B想要继承父类A中的所有属性和方法(私有+公有),只需要让`B.prototype = new A`即可 原型继承的特点: - 它是把父类中私有的+公有的都继承到子类原型上(子类公有的) - 支持重写(子类通过`__proto__`修改祖先类的属性和方法) - 需要手动修正`constructor` 核心:原型继承并不是把父类中的属性和方法克隆一份一模一样的给B,而是让B和A之间增加了原型链的连接,以后B的实例n想要A中的getX方法,需要一级级的向上查找来使用。 ``` function Object(){ } Object.prototype = { constructor:Object ,hasOwnProperty:function(){} ,... } function EventTarget(){ } EventTarget.prototype = new Object(); EventTarget.prototype.addEventListener = function(){}; function Node(){} Node.prototype = new EventTarget; Node.prototype.createElement = function(){} var node = new Node; //最后修正constructor ``` ![](https://box.kancloud.cn/8776150ddf30da62f2b17aef1b6648eb_431x252.png) ``` function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); }; function B(){ this.y = 200; } B.prototype = new A; B.prototype.constructor = B; ``` ![](https://box.kancloud.cn/bef2d91ea11a59d71852ab016e297564_1543x801.png) ## call继承 `call`继承最终的结果:会把父类私有的属性和方法 克隆一份一模一样的 作为子类私有的属性,和父类**没有直接关系**。 ``` function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); }; function B(){ //this->n A.call(this); //A.call(n) 把A执行让A中的this变为了n } ``` ``` var n = new B; console.log(n.x); ``` ## 冒充对象继承 把父类私有的+公有的克隆一份一模一样的给子类私有的 ``` function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); }; function B(){ //this-> var temp = new A; for(var key in temp){ //不能用hasOwnProperty进行判断,否则会继承不到公有的 this[key] = temp[key] } temp=null; } var n = new B; ``` ## 混合模式继承 原型继承+call继承 ``` function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); }; function B(){ A.call(this); //->n.x=100 } B.prototype = new A; //->B.prototype:x=100 getX... B.prototype.constructor = B; ``` 优势在于B的实例b自己身上拥有A的私有属性而不是通过`__proto__`查找。 ## 寄生组合式继承 ``` function A(){ this.x = 100; } A.prototype.getX = function(){ console.log(this.x); }; function B(){ A.call(this); //->n.x=100 } B.prototype = Object.create(A.prototype); B.prototype.constructor = B; ``` ``` function objectCreate(o){ function fn(){}; fn.prototype = o; return new fn; } ``` ## 中间类继承法 ``` arguments.__proto__ = Array.prototype ```