js实现继承
js实现继承主要有六种方式。
1.通过构造函数继承
function Parent() { this.name = 1; } function Children() { Parent.call(this); console.log(this.name); }
重点是在子函数内通过call()调用父函数,将父函数的构造函数为子类添加实例。
优点:简单明了,继承父函数的属性和方法。
缺点:不可以继承原型链上的属性和方法。
2.通过原型链继承
function Parent() { this.name = 1; } function Children() { } Children.prototype = new Parent(); Children.prototype.constructor = Children;
重点在于子函数外声明原型是父类的一个实例,而constructor为子类的构造函数。
优点:简单明了,实例是子类实例,同时也是父类的一个实例。子类可以访问到父类原型上的方法.
缺点:缺点也很明显,所有子类共享一个实例的属性和方法。
3.组合继承
function Parent() { this.name = 1; } function Children() { Parent.call(this); } Children.prototype = new Parent(); Children.prototype.constructor = Children;
优点:解决了构造函数继承和通过原型链继承的缺点。
缺点:子类实例会继承父类实例的两份属性,子类的属性会覆盖父类属性。
4.原型式继承
function getChild(obj) { function Child() {} Child.prototype = obj; return new Child(); }
重点为不需要显示定义父类,直接继承对象。
优点:直接继承对象。
缺点:不是类的继承。
5.寄生式继承
function getChild(obj) { function Child() {} Child.prototype = obj; return new Child(); } function clone(obj){ var cloneObj = objectCreate(obj); cloneObj.newProperty = 'new property'; return cloneObj; }
重点在于封装一个继承过程的一个函数,并在函数内进行增强。
优点:原型式继承的一种拓展。
缺点:仍没有类的概念。
6.组合寄生式继承
function Parent() { this.name = '1234'; } function Children() { Parent.call(this); } function inheritPrototype(Parent,Children) { var newObg = objectCreate(Parent.prototype); Children.prototype = newObj; newObj.constructor = Children; }
优点:较为完美。
缺点:过程繁琐。