Open K0II opened 8 years ago
'use strict';
// 定义一个构造器并扩充它的原型
var Mammal = function(name) {
this.name = name;
};
Mammal.prototype.getName = function() {
return this.name;
};
Mammal.prototype.say = function() {
return this.saying || '';
};
// 构造一个实例
var myMammal = new Mammal('Herb the Mammal');
var name = myMammal.getName(); // Herb the Mammal
// 构造一个伪类来继承 Mammal
var Cat = function(name) {
this.name = name;
this.saying = 'meow';
};
// 替换 Cat.prototype 为一个新的 Mammal 实例
Cat.prototype = new Mammal();
Cat.prototype.__proto__ === Mammal.prototype; // true
// Car 和 Mammal 没有关系,Cat.prototype 的原型链指向 Mammal.prototype
// 扩充新原型对象,增加 purr 和 getName 方法
Cat.prototype.purr = function(n) {
var i;
var s = '';
for (i=0;i<n;i++) {
if (s) {
s += '-';
}
s += 'r'
}
return s;
}
Cat.prototype.getName = function() {
return this.say() + ' ' + this.name + ' ' + this.say();
}
var myCat = new Cat('Henrietta');
var say = myCat.say(); // meow
var purr = myCat.purr(5); // r-r-r-r-r
var name = myCat.getName(); // meow Henrietta meow
'use strict';
// 先构造一个对象
var myMammal = {
name: 'Herb the Mammal',
getName: function() {
return this.name;
},
say: function() {
return this.saying || '';
}
}
// 定制新的实例
var myCat = Object.create(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.purr = function(n) {
var i;
var s = '';
for (i=0;i<n;i++) {
if (s) {
s += '-';
}
s += 'r'
}
return s;
};
myCat.getName = function() {
return this.say() + ' ' + this.name + ' ' + this.say();
};
myCat.say(); // meow
myCat.purr(5); // r-r-r-r-r
myCat.getName(); // meow Henrietta meow
以上的继承模式的一个弱点是没办法保护隐私,对象的所有属性都是可见的。
我们无法得到私有变量和私有函数。
模块模式
'use strict';
// 构造器 mammal
var mammal = function(spec) {
var that = {};
that.getName = function() {
return spec.name;
},
that.say = function() {
return spec.saying || '';
};
return that;
};
var myMammal = mammal({name: 'Herb'});
// 构造器 cat
var cat = function (spec) {
spec.saying = spec.saying || 'meow';
var that = mammal(spec);
that.purr = function (n) {
var i, s = '';
for (i = 0; i < n; i += 1) {
if (s) {
s += '-';
}
s += 'r';
}
return s;
};
that.getName = function() {
return that.say() + ' ' + spec.name + ' ' + that.say();
};
return that;
};
var myCat = cat({name: 'Henrietta'});
Object.prototype.superior = function(name) {
var that = this;
var method = this[name];
return function() {
return method.apply(that,arguments);
};
};
// 构造器 coolcat
var coolcat = function(spec) {
var that = cat(spec),
super_get_name = that.superior('getName');
that.getName = function() {
return 'like ' + super_get_name() + ' baby';
};
return that;
};
var myCoolCat = coolcat({name: 'Bix'});
myCoolCat.getName(); // like meow Bix meow baby
that that that that that that that that that that that that
如果对象的所有状态都是私有的,那么该对象就成为一个防伪(tamper-proof)对象。该对象的属性可以被替换或删除,但该对象的完整性不会受到损害
如果我们用函数化的样式去创建一个对象,并且该对象的所有方法都不使用that
或this
,那么该对象就是持久性(durable)。一个持久性对象就是一个简单功能函数的集合
扩充类型的功能 ( Augmenting Types )