js的继承方式

mac2026-06-11  15

一、构造函数继承

改变this指向继承 只能继承构造函数中this身上的属性和方法,不能继承原型身上的属性和方法 三种方法: 1、.call(this); 2、.apply(this); 3、.bind(this,n)(); function Parent(n){ this.num = n; this.show = function(){ console.log(this.num); } } Parent.prototype.init = function(){ console.log(123); } function Child(n){ //想在C中使用P的方法和属性 //P的方法和属性加给谁了?this //P中的this是将来new出来的p //C中this是将来new出来的c //c要执行show 在C中的this要有show //没有,P的this有onshow //强行将P的this指向C的this //哪里能拿到C的this?在C中 //这里是写在C中的 所以这里的this是C的this // Parent.call(this); // Parent.apply(this); Parent.bind(this,n)(); } var p = new Parent(3.1415); p.show(); p.init(); var c = new Child(520); c.show(); //不能继承原型身上的属性和方法 // c.init();

二、原型对象继承

只能继承原型身上的属性和方法,不能继承构造函数中this的属性和方法 原型是一个对象,直接将原型作为一个对象复制,注意对象的深浅拷贝 // for(var i in Parent.prototype){ Child.prototype[i] = Parent.prototype[i]; } //遍历进行深拷贝 function Parent(n){ this.num = 123; this.show = function(){ console.log(this.num); } } Parent.prototype.init = function(){ console.log("hello"); } function Child(n){} //原型是一个对象 //直接将原型作为一个对象复制 //注意对象的深浅拷贝 // Child.prototype = Parent.prototype; //遍历进行深拷贝 for(var i in Parent.prototype){ Child.prototype[i] = Parent.prototype[i]; } Child.prototype.init = function(){ console.log("html"); } var p = new Parent(3.1415); p.init(); console.log(p.num); var c = new Child(520); c.init(); console.log(c.num);

三、原型继承–原型链

既能继承原型的属性和方法,又能继承构造函数的属性和方法 缺点:不方便传参 function Parent(n){ this.num = n; } Parent.prototype.init = function(){ console.log("hello"); } function Child(n){} //c的父级 等于Parent的儿子 p(降了两级) //参数要在这里传 //这里new的实例 才是c的父级 它和上面实例的p不是一个 Child.prototype = new Parent(520); //这是深复制 改写不影响P Child.prototype.init = function(){ console.log("html"); } var p = new Parent(3.1415); p.init(); console.log(p.num); var c = new Child(); c.init(); console.log(c.num); console.log(p); console.log(c);

四、混合继承

混合继承 : 常用的继承方式之一 构造函数继承 + 原型对象继承 function Parent(n){ this.num = n; } Parent.prototype.init = function(){ console.log("hello"); } function Child(n){ Parent.call(this,n) } for(var i in Parent.prototype){ Child.prototype[i] = Parent.prototype; } Child.prototype.init = function(){ console.log("html"); } var p = new Parent(3.1415); p.init(); console.log(p.num); var c = new Child(123); c.init(); console.log(c.num);

五、es6的继承

原理:封装改变this指向继承和原型链继承 优点:方便简单 缺点:没有普遍浏览器的支持 class Parent{ constructor(n){ this.name = n; } show(){ console.log(this.name + "执行了show"); } } class Child extends Parent{ constructor(n){ //加超级函数传参 super(n); } show(){ console.log(123); } } var p = new Parent("zhangsan"); p.show(); var c = new Child("lisi"); c.show();
最新回复(0)