function A() { this.x = 100; } A.prototype.getX = function getX() { console.log(this.x); }; function B() { this.y = 200; } B.prototype.sum=function(){} B.prototype = new A; //B子类 => A父类,让子类B的原型指向父类A的实例
B.prototype.getY = function getY() { console.log(this.y); }; let b = new B;
通过B.prototype = new A这一句话达成继承。
js中的面向对象的机制都是基于原型链完成的,所以js中的继承也可以是基于原型链的,但这其中又有很多弊端。
比如B之前的原型B.prototype上的方法b已经查找不到,b的constructor应该是B,但现在是A,b可以通过b.__proto__或b.__proto__.__proto__肆意修改父类上的属性和方法,而父类上不管私有还是公有的属性和方法都会成为子类公有的,这些种种问题都是需要注意的,这大概就是IE浏览器禁止使用__proto__的原因吧。
function A() { this.x = 100; } A.prototype.getX = function getX() { console.log(this.x); }; function B() { //call继承 A.call(this); //=>this.x = 100; => b.x=100; this.y = 200; } B.prototype.getY = function getY() { console.log(this.y); }; let b = new B;
function A() { this.x = 100; } A.prototype.getX = function getX() { console.log(this.x); }; function B() { A.call(this); this.y = 200; } //=>Object.create(OBJ) 创建一个空对象,让其__proto__指向OBJ(把OBJ作为空对象的原型) B.prototype = Object.create(A.prototype); B.prototype.constructor = B; //把constructor补上 B.prototype.getY = function getY() { console.log(this.y); }; let b = new B; console.log(b);
class A { constructor() { this.x = 100; } getX() { console.log(this.x); } } //=>extends继承和寄生组合继承基本类似 class B extends A { constructor() { super(); //=>一但使用extends实现继承,只要自己写了constructor,就必须写super this.y = 200; } getY() { console.log(this.y); } } let b = new B;
原文:https://www.cnblogs.com/ronaldo9ph/p/12392064.html