赞
踩
继承是基于“类”的,在没有es6前,一个用来new的函数就充当了“类”的构造函数,构造函数的prototype上面的属性就等于实例的共享属性。
这篇文章主要记录使用函数实现常见的2种继承方式,理解了这2种继承方式,其他的都不再难理解了
- function Parent(name){
- this.name=name;
- }
- Parent.prototype.myname=function(){
- console.log("name:"+this.name)
- }
-
- function Child(){}
- //直接引用
- Child.prototype=Parent.prototype;
- var child=new Child("小明");
- console.log("child",child)
- child.myname();//undefined
直接引用,Parent的prototype属性变化时候也会被变化
无法调用“父类”的构造函数,导致无法初始化实例属性
- function Parent(name){
- this.name=name;
- }
- Parent.prototype.myname=function(){
- console.log("name:"+this.name)
- }
-
- function Child(...arg){
- //直接牵复制
-
- Parent.call(this,...arg)
- }
- var child=new Child("小明");
- console.log("child",child.name)
无法继承父类的prototype方法
结合原型链和构造函数继承的优点
- function Parent(name){
- this.name=name;
- }
- Parent.prototype.myname=function(){
- console.log("name:"+this.name)
- }
-
- function Child(...arg){
- //直接牵复制
-
- Parent.call(this,...arg)
- }
- Child.prototype=Parent.prototype;
- var child=new Child("小明");
- console.log("child",child)
- child.myname();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。