JavaScript继承

2019-03-08  本文已影响0人  广告位招租

以下栗子都会使用一个公共的父类

// 创建一个父类
    function Animal(name) {
        this.name = name || 'Animal';
        this.sleep = function() {
            console.log(this.name + ' 正在睡觉')
        }
    }

    Animal.prototype.eat = function(food) {
        console.log(this.name + ' 正在吃 ' + food);
    }

1. 基于原型链的继承

将上级函数的实例赋值给下级函数的原型

// 新建一个Cat类
function Cat(lname) {
    this.lname = lname
    this.say = function() {
        console.log('喵~')
    }
}

// 将上级函数的实例复制给下级函数的原型prototype
Cat.prototype = new Animal()
// 但是要想给子类的原型新增方法,需要在new Animal()语句之后进行
Cat.prototype.cname = 'sigoudaner' 

// 新建一个cat类
let cat = new Cat('goudaner', '小明')

console.group()
console.log(cat.name, '---cat.name')
console.log(cat.lname, '---cat.lname')
console.log(cat.cname, '---cat.cname')
cat.say()
cat.sleep()
cat.eat('yu')
console.log(cat instanceof Animal) // true
console.log(cat instanceof Cat) // true
image.png

构造继承

使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)

// 构造继承
function Cat(name) {
    Animal.call(this);
    this.name = name || 'goudaner'
}
let cat = new Cat()

console.group()
console.log(cat.name)
cat.sleep()
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)
cat.eat('鱼')
image.png

实例继承

为父类实例添加新特性,作为子类实例返回

function Cat(name){
    var _Cat = new Animal();
    _Cat.name = name || 'goudaner';
    _Cat.lname = 'sigoudaner';
    return _Cat; // 将父类的实例添加新特性之后,作为子类的实例返回
}

// 声明实例可以有两种方式
let cat = new Cat()
let cat = Cat()

console.group()
console.log(cat.name)
console.log(cat.lname)
cat.sleep()
cat.eat('鱼')
console.log(cat instanceof Animal) // true
console.log(cat instanceof Cat) // false

组合继承

将原型链继承和构造继承组合使用

function Cat(name){
    Animal.call(this);
    this.name = name || 'goudaner';
}
// 比构造继承就多了下面这句话
Cat.prototype = new Animal();

var cat = new Cat();

console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true

es6实现继承

相对于继承更加友好

class Cat extends Animal {
    constructor(name) {
        super()
        this.name = name
    }
    say() {
        console.log('喵~')
    }
}

let cat = new Cat('goudaner')

console.group()
console.log(cat.name)
cat.sleep()
cat.eat('鱼')
cat.say()
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)
image.png

关于原理请点击详情

上一篇 下一篇

猜你喜欢

热点阅读