标签:es5 color fun style 对象 构造 div col tor
怎么声明也一个类
//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
标签:es5 color fun style 对象 构造 div col tor
原文地址:https://www.cnblogs.com/sunnywindycloudy/p/13027855.html