JavaScript的继承
一.ES6 class 继承:
1.class继承实际上是构造函数的继承和原型链继承的综合封装
2.class继承优点是操作简单, 即可以继承原型又可以继承 构造函数
2.实现的方法:关键字extend和super
3.实例:
constructor(n){
this.name=n;
}
say(){
console.log('我是'+this.name);
}
}
class Child extends Parent{//继承的实现方式
constructor(n){
super(n);
}
}
var p1=new Parent('张钦');
p1.say();
var p2=new Child('李四');
p2.say();
二.构造函数继承
1.构造函数与构造函数之间的继承,实质是改变函数的this指向,利用blind
2.优点:简单易操作可以实现多继承
缺点:只能继承构造函数中的内容,不能继承原型上的内容;
4.实例:
function Parent(n){
this.name=n;
this.say=function(){
console.log('你好'+this.name);
}
}
Parent.prototype.show=function(){
console.log('欢迎您的到来')
}
function Child(n){
Parent.bind(this,n)();//改变构造函数的this为child
//Parent.call(this,n);//call与this作用一样,但他是自执行
//Parent.apply(this,[n]);//apply与this的功能一样,但是形参必须放在数组中
}
var p1=new Parent('张钦');
var p2=new Child('李四')
p1.say();
p1.show();
p2.say();
p2.show();// 报错
三:原型继承
1.利用函数的prototype相等去实现;
2.优点:
缺点:可以继承到构造函数和原型上的东西,但是不方便传参
3.bug版:对象的浅拷贝引起的
function Parent(n){
this.name=n;
this.say=function(){
console.log('你好'+this.name);
}
}
Parent.prototype.show=function(){
console.log('欢迎您的到来')
}
function Child(n){
}
Child.prototype=Parent.prototype;
Child.prototype.show=function(){//对象的引用传递会使Parent的show也发生变化
console.log('欢迎下次光临');
}
var p1=new Parent('张钦');
var p2=new Child('李四')
p1.say();
p1.show();//
//p2.say();// 报错,但是不能继承构造函数上的内容
p2.show();//继承了原型上的内容
4.完整版:解决方式:1.原型方式2.对象方式(1.for in2.json对象转化)
function Parent(n){
this.name=n;
}
Parent.prototype.show=function(){
console.log('欢迎您的到来')
}
function Child(n){
}
Child.prototype=new Parent();//将Parent的实例作为Child.prototype的父,这样Child.prototype就能沿着实例Parent找到他的父Parent的父Parent.prototype;
var p1=new Parent('张钦');
var p2=new Child('李四')
console.log(p1);
console.log(p2);
p1.show();
p2.show();
四:混合继承
混合继承:将构造函数继承和原型继承结合
实例:最终完整版(案例实战版)
function Parent(n){
this.name=n;
this.say=function(){
console.log('你好'+this.name);
}
}
Parent.prototype.show=function(){
console.log('欢迎您的到来')
}
function Child(n){
Parent.bind(this,n)();
}
Child.prototype=new Parent();//一原型的方式二以对象的方式(未写)
Child.prototype.show=function(){//注意要写自己方法或属性时要写在继承的后面
console.log('欢迎下次光临');
}
var p1=new Parent('张钦');
var p2=new Child('李四');
p1.say();
p1.show();
p2.say();
p2.show();


被折叠的 条评论
为什么被折叠?



