码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript继承总结

时间:2018-09-03 00:01:52      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:实现继承   sleep   利用   cto   增加   无法   javascrip   pre   父类   

1.创建对象

1.字面量对象
2.构造函数
3.Object.create

//1.字面量
var obj={
    name: ‘字面量‘,
    show: function(){
        console.log(this.name)
    }
}
//2.构造函数
function fun (name) {
    this.name=name
}
var obj=new fun(‘obj‘)
//3.Object.create
var obj={name: ‘obj‘}
var obj=Object.create(obj)

2.JavaScript继承

1.原型链继承

function Parent(name){
    this.name=name
    this.sleep=function(){
        console.log(this.name + ‘在睡觉‘)
    }
}
Parent.prototype.eat=function(food){
    console.log(this.name + ‘正在吃‘ + food)
}
function Child(){}
Child.prototype=new Parent(‘Child‘)
Child.prototype.constructor=Child
var child=new Child()

Child.prototype=new Parent(‘Child‘)就是把Parent实例赋值给Child.prototype,也就是说new Child().__proto__===new Parent(‘Child‘)

可以通过Child.prototype在原型对象上增加新的属性或方法,也可以通过,child.__proto__在原型对象上添加新的方法和属性。

缺点:
1.原型对象上的属性和方法是所有实例都可访问的,而且一个实例改变了原型上的方法和属性都会影响到其他实例。
2.创建子类实例时,无法向父类构造函数传参。

2.构造函数继承

function Parent(name){
    this.name=name
    this.sleep=function(){  
        console.log(this.name + ‘在睡觉‘)
    }
}
Parent.prototype.eat=function(food){
    console.log(this.name + ‘正在吃‘ + food)
}

function Child(){
    Parent.call(this,‘child‘)
}
Child.prototype.eyes=function(){console.log(‘eyes‘)}
var child=new Child()

构造函数继承可以通过call或apply方法实现继承。这种方法不能继承原型对象中的属性和方法,只能继承实例属性和实例方法,但是可以向父类传参。

3.组合继承

function Parent(name){
    this.name=name
    this.sleep=function(){  
        console.log(this.name + ‘正在睡觉‘)
    }
}
Parent.prototype.eat=function(food){
    console.log(this.name + ‘正在吃‘ + food)
}
function Child(){
    Parent.call(this,‘child‘)
}
Child.prototype.eyes=function(){console.log(‘eyes‘)}

Child.prototype=new Parent()
Child.prototype.constructor=Child 
var child=new Child()

组合继承是比较好的继承, 他是原型链继承和构造函数继承的结合, 合理的利用了这两种组合的特点,既是子类的实例,也是父类的实例, 但有一个缺点就是调用了两次构造函数。

4.组合继承优化

function Parent(name){
    this.name=name
    this.sleep=function(){  
        console.log(this.name + ‘正在睡觉‘)
    }
}
Parent.prototype.eat=function(food){
    console.log(this.name + ‘正在吃‘ + food)
}
function Child(){
    Parent.call(this,‘child‘)
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor=Child 
var child=new Child()

5.寄生组合继承

function Parent(name){
    this.name=name
    this.sleep=function(){  
        console.log(this.name + ‘正在睡觉‘)
    }
}
Parent.prototype.eat=function(food){
    console.log(this.name + ‘正在吃‘ + food)
}
function Child(){
    Parent.call(this,‘child‘)
}
function f(){}
f.prototype=Parent.prototype
Child.prototype=new f()
Child.prototype.constructor=Child 
var child=new Child()

只调用一次父类的构造函数,避免了在子类原型上创建不必要的,多余的属性。

JavaScript继承总结

标签:实现继承   sleep   利用   cto   增加   无法   javascrip   pre   父类   

原文地址:https://www.cnblogs.com/qfstudy/p/9575663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!