一、构造函数法(最常用)
function Cat() {
this.name = "大毛";
}
var cat1 = new Cat();
console.log(cat1.name); // 大毛
主要缺点是,比较复杂,用到了this和prototype,编写和阅读都很费力
二、Object.create()法(ES5特性)
var Cat = {
name: "大毛",
makeSound: function(){console.log("喵喵喵");}
};
var cat1 = Object.create(Cat);
console.log(cat1.name); // 大毛
cat1.makeSound(); // 喵喵喵
三、极简主义法(在对象里定义一个构造函数,返回实例)
1.封装
var Cat = {
createNew: function(){
var cat = {
name:"大毛",
makeSound:function(){console.log("喵喵喵");}
};
return cat;
}
};
var cat1 = Cat.createNew();
cat1.makeSound(); // 喵喵喵
2.继承
var Animal = {
createNewAnimal: function(){
var animal = {
sleep:function(){ console.log("睡懒觉"); }
};
return animal;
}
};
var Cat = {
createNewCat: function(){
var cat = Animal.createNewAnimal();
cat.name = "大毛";
cat.makeSound = function(){ console.log("喵喵喵"); };
return cat;
}
};
var cat1 = Cat.createNewCat();
cat1.sleep(); // 睡懒觉
3.私有变量和方法(在createNew()方法中,只要不是定义在cat对象上的方法和属性,都是私有的,无法读取。)
var sound="哈哈哈";
var Cat = {
createNew: function(){
sound="喵喵喵";
var cat = {
makeSound:function(){ console.log(sound); }
};
return cat;
}
};
var cat1 = Cat.createNew();
cat1.makeSound();//喵喵喵
console.log(cat1.sound); // undefined
console.log(cat1.makeSound);//function (){ console.log(sound); }
4.数据共享(只要把这个内部数据,封装在类对象的里面、createNew()方法的外面即可)
var Cat = {
sound : "喵喵喵",
createNew: function(){
var cat = {
makeSound:function(){ console.log(Cat.sound); },
changeSound:function(x){ Cat.sound = x; }
};
return cat;
}
};
var cat1 = Cat.createNew();
var cat2 = Cat.createNew();
cat1.makeSound(); // 喵喵喵
cat2.changeSound("啦啦啦");
cat1.makeSound(); // 啦啦啦