Javascript中的继承

本文深入探讨了JavaScript中的七种继承方法:原型链继承、构造函数继承、组合继承、原型式继承、寄生式继承、寄生组合式继承和寄生组合式继承。通过示例代码展示了每种方法的工作原理及优缺点,帮助读者理解JavaScript对象间的继承机制。
摘要由CSDN通过智能技术生成
  1. 继承方法:
原型链继承
构造函数继承(借助 call)
组合继承
原型式继承
寄生式继承
寄生组合式继承

2.原型链继承

function fun(){
this.obj = 1;
this.foo = function foo(){
console.log(this.obj);
}
}
function fun1(){
this.obj = 2
}
fun1.prototype = new fun();
console.log(new fun1().foo())//2

3.构造函数继承

function fun(){
this.name = 'mike';
this.age = 18;
this.foo = function foo(){
console.log(this.name);
}
}
fun.prototype.getName = function getName(){
console.log(this.name);
}
function fun1(){
fun.call(this);
this.gride = 'man';
}
console.log(new fun().getName(),new fun1().foo(),new fun1().getName())
// mike mike error

4.组合继承

function fun(){
this.name = 'mike';
this.age = 18;
this.foo = function foo(){
console.log(this.name);
}
}
fun.prototype.getName = function getName(){
console.log(this.name);
}
function fun1(){
fun.call(this);
this.gride = 'man';
}
fun1.prototype = new fun();
fun1.constructor = fun1;
console.log(new fun().getName(),new fun1().foo(),new fun1().getName())
//mike mike mike

5.原型式继承

let fun = {
name:'mike',
age: 18,
foo: function foo(){
console.log(this.name)
}
}
fun1 = Object.create(fun);
console.log(fun.foo(),fun1.name)//mike,mike

6.寄生式继承

//寄生式继承在原型式继承基础上进行优化,利用这个浅拷贝的能力再进行增强,添加一些方法
let animal = {
    name:'zhangsan',
    age:18,
    getName: function(){
        return this.name
    }
}
function clone(obj){
 const cloneObj = Object.create(obj);
    cloneObj.getAge = function (){
        return this.age;
    }
    return cloneObj;
}
const obj = clone(animal);
console.log(obj.getName(),obj.getAge());//zhangsan 18

7.寄生组合式继承

function clone (parent, child) {
    // 这里改用 Object.create 就可以减少组合继承中多进行一次构造的过程
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;
}

function Parent6() {
    this.name = 'parent6';
    this.play = [1, 2, 3];
}
Parent6.prototype.getName = function () {
    return this.name;
}
function Child6() {
    Parent6.call(this);
    this.friends = 'child5';
}

clone(Parent6, Child6);

Child6.prototype.getFriends = function () {
    return this.friends;
}

let person6 = new Child6(); 
console.log(person6); //{friends:"child5",name:"child5",play:[1,2,3],__proto__:Parent6}
console.log(person6.getName()); // parent6
console.log(person6.getFriends()); // child5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值