JS中常见的几种继承方法

1.原型链继承

 1 // 1.原型链继承
 2 /* 
 3     缺点:所有属性被共享,而且不能传递参数
 4 */
 5 function Person(name,age){
 6     this.name = name
 7     this.age = age
 8 }
 9 Person.prototype.sayName = () =>{
10     console.log(this.name)
11 }
12 function Man(name){
13     
14 }
15 Man.prototype = new Person()
16 Man.prototype.name = 'zhangsan'
17 var zhangsan = new Man('zhangsan')
18 console.log(zhangsan.name) //zhangsan

2.构造函数继承(经典继承)

// 构造函数继承(经典继承)
/* 
    优点:可以传递参数
    缺点:所有方法都在构造函数内,每次创建对象都会创建对应的方法,大大浪费内存
*/
function Perent(name,age,sex){
    this.name = name
    this.age = age
    this.sex = sex
    this.sayName = function(){
        console.log(this.name)
    }
}

function Child(name,age,sex){
    Perent.call(this,name,age,sex)
}
let child = new Child('lisi' , 18, '男')
console.log(child)   //Child { name: 'lisi', age: 18, sex: '男', sayName: [Function] }

3.组合方式继承(构造函数 + 原型链)

// 3.组合模式(构造函数 + 原型链)
/* 
    这种方式充分利用了原型链与构造函数各自的优点,是JS中最常用的继承方法

*/
function Animal(name,age){
    this.name = name
    this.age = age
}
Animal.prototype.sayName = function () {
    console.log(this.name)
}
function Cat(name,age,color){
    Animal.call(this,name,age)
    this.color = color
}
Cat.prototype = Animal.prototype  //将Cat的原型指向Animal的原型
Cat.prototype.constructor = Cat   //将Cat的构造函数指向Cat
let cat = new Cat('xiaobai',3,'white')
console.log(cat) //Cat { name: 'xiaobai', age: 3, color: 'white' }
cat.sayName()   //xiaobai

4.es6方法继承

// 4.es6继承方法
class Per {
    constructor(name){
        this.name = name
    }
    sayName(){
        console.log(this.name)
    }
}

class Son extends Per{
    constructor(name,age){
        super(name)
        this.age = age
    }
}
let son = new Son('zhangsan',18)
console.log(son) //Son { name: 'zhangsan', age: 18 }
son.sayName() //zhangsan

 

转载于:https://www.cnblogs.com/songyao666/p/11427113.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值