【面向对象】JS封装方法

普通:

var catA = {
    name:'xiaoA',
    eat:function(){
        console.log('xiaoA eat something')
    }
}

var catB = {
    name:'xiaoB',
    eat:function(){
        console.log('xiaoB eat something')
    }
}

var catC = {
    name:'xiaoC',
    eat:function(){
        console.log('xiaoC eat something')
    }
}

 

封装:

1、工厂模式进行封装

function createCat(name){
     var obj={}
     obj.name = name;
     obj.eat = function(){
           console.log(name + 'eat something');
      }
      return obj;
}

var catA = createCat('xiaoA');
var catB = createCat('xiaoB');
var catC = createCat('xiaoC'); 

 

2、面向对象的方式进行封装

function CreateCat(name){
     this.name = name;
     this.eat = function(){
           console.log(this.name + 'eat something');
     }
}
        
var catA = new CreateCat('xiaoA');
var catB = new CreateCat('xiaoB');
var catC = new CreateCat('xiaoC');

 

posted @ 2020-04-02 01:22  -加勒比海参  阅读(320)  评论(0编辑  收藏  举报