普通:
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');