前言
很久很久以前,单身狗还不是一条狗的时候。上帝为了物种的多样性准备弄出一只单身狗。
1. 手工作坊生产单身狗
直接通过Object创建实例
var dog1 = {
type: '哺乳动物',
color: '黑色',
level: '中华田园犬'
};
var dog2 = {
type: '哺乳动物',
color: '白色',
level: '哈士奇'
};
缺点:
现在我要20条狗,那么就需要手工制造20次。同时单身狗是看不出之间的关系的,只能看出单身狗们跟上帝有直接的关系。
举例:
var dog1 = {
type: '哺乳动物',
color: '黑色',
level: '中华田园犬'
};
var dog2 = {
type: '哺乳动物',
level: '哈士奇'
name: '富兰克林',
};
2. 上帝太忙,委托生产线生产单身狗
function Dog(type, color, level) {
return {
type: type,
color: color,
level: level
};
}
var dog1 = Dog('哺乳动物', '黑色', '中华田园犬');
var dog2 = Dog('哺乳动物', '白色', '哈士奇');
解决了上帝重复劳动的问题(代码重复问题解决了),可是单身狗之间依然不能建立除跟上帝以外的其他关系。
3. OEM时代
OEM:原始设备制造商
function SNDog(type, color) {
this.type = type;
this.color = color;
}
var dog1 = new SNDog('哺乳动物', '黑色');
var dog2 = new SNDog('哺乳动物', '白色');
单身狗被制造出来之后,他们都出自同一个工厂,叫做 ‘SNDog’。
这种单身狗生来就有一个属性指向工厂,这个属性叫做:constructor。
这下 dog1 和 dog2 就有关系了:
dog1.constructor === dog2.constructor; // true
3.1 工厂的技术人员说,有些工作量是重复的
function Dog(type, color) {
this.type = type;
this.color = color;
this.eat = function() {
// TODO 喂狗粮省去1000行代码
}
}
var dog1 = new Dog('哺乳动物', '黑色');
var dog2 = new Dog('哺乳动物', '白色');
喂狗粮的方法在每次实例化 Dog 时,都会生成一个副本占用内存。那么现在出现了20条单身狗,内存就弄出了20000行代码,看起来实在不经济不实惠。
4. 为了节约
function Dog(type, color) {
this.type = type;
this.color = color;
}
Dog.prototype.eat = function() {
// TODO 喂狗粮省去1000行代码
};
var dog1 = new Dog('哺乳动物', '黑色');
var dog2 = new Dog('哺乳动物', '白色');
证明:
function MarriedDog(name) {
this.name = name;
this.eat = function() {
console.log(this.name);
};
};
var md1 = new MarriedDog('1');
var md2 = new MarriedDog('2');
console.log(md1.eat === md2.eat); // false
function SingleDog(name) {
this.name = name;
}
SingleDog.prototype.eat = function() {
console.log(this.name);
};
var sd1 = new SingleDog('3');
var sd2 = new SingleDog('4');
console.log(sd1.eat === sd2.eat); // true
上面的例子间接说明‘单身狗’更节约
结语
上帝成功的创造出了单身狗