面向对象

类的声明

function   Animal () {
     this.name = "name";
}

ES6中的类的声明

class Animal {
   constructor () {
        this.name = name;
   }

}


类的声明
function Animal () {
		this.name = "Jack"
}
ES6中的class的声明
class Animal2 {
   constructor (){
         this.name = name
   }
}

JS继承的实现方式

//定义一个动物类
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 原型链继承


核心:将父类的实例作为子类的原型

function  Cat(){
}
Cat.prototype = new  Animal();
Cat.prototype.name = 'cat'

var cat = new Cat();
console.log(cat.name)
console.log(cat.sleep())

2 构造继承

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

function Cat(name) {
  Animal.call(this);
  this.name = name || "Tom";
}

var  cat = new  Cat();
console.log(cat.name)
console.log(cat.sleep())
console.log(cat  instanceof Animal);  //false
console.log(cat  instanceof   Cat);   //true

注意:不能继承构造函数中原型对象中的方法和属性

3 实例继承

function Cat(name) {
    var  instance = new  Animal()
    instacne.name = name || "Tom";
    return   instance
}

var cat = new  Cat()
console.log(cat  instanceof  Animal)  //true
console.log(cat  instanceof  Cat)  //false

4 拷贝继承

function  Cat(name) {
     var    animal = new  Animal();
     for( var p in animal ) {
         Cat.prototype[p] = animal[p];
   }
   Cat.prototype.name = name || "Tom';
}


var   cat = new  Cat();
console.log(cat.name)
console.log(cat instanceof  Animal);  //false
console.log(cat instanceof  Cat) ; //true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值