Class

Posted sunnywindycloudy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Class相关的知识,希望对你有一定的参考价值。

Class

怎么声明也一个类

//ES5
let Animal=function(type){
    this.type=type;
    this.eat=function(){
        console.log(‘i am eat food‘);
    }
}

let dog=new Animal(‘dog‘);
let monkey=new Animal(‘monkey‘);

console.log(dog);
console.log(monkey);

monkey.eat=function(){
    console.log(‘error‘);
}

dog.eat();
monkey.eat();

//缺点:每个实例都各自有eat(),不能共用,违背继承的原则

//以上例子修改为
let Animal=function(type){//构造函数,实例对象独有的东西放这里
    this.type=type;
}
Animal.prototype.eat=function(){//共有的东西都写在prototype里
    console.log(‘i am eat food‘);
}
monkey.constructor.prototype.eat=function(){//可以改变共同的方法
    console.log(‘error‘);
}

//ES6
class Animal{
    constructor(type){
        this.type=type;
    }
    eat(){
        console.log(‘i am eat food‘);
    }
}
let dog=new Animal(‘dog‘);
let monkey=new Animal(‘monkey‘);
console.log(dog);
console.log(monkey);
dog.eat();
monkey.eat();

console.log(typeof Animal);//function

 

以上是关于Class的主要内容,如果未能解决你的问题,请参考以下文章