JavaScript Good Parts学习笔记-继承篇
JavaScript是一个弱类语言,从不需要类型转换,对象继承关系变得无关紧要,对于一个对象来说,重要的是它能做什么,而不是它从哪里来。
1。伪类(Pseudoclassical)
当一个函数对象被创建时,Function构造器产生的函数对象会运行类似这样的一段代码
this.prototype = {constructor: this};
当采用构造器调用模式,(即使用new),可能会像下面那样执行
Function.method('new', function ( ) {
// Create a new object that inherits from the
// constructor's prototype.
var that = Object.create(this.prototype);
// Invoke the constructor, binding –this- to
// the new object.
var other = this.apply(that, arguments);
// If its return value isn't an object,
// substitute the new object.
return (typeof other === 'object' && other) || that;
});
看起来像继承,但是,
没有私有环境,所有属性都是公开的,不能调用父类的方法。
更糟糕的是,如果你忘记使用new,this则不会被绑定到新对象上,而是绑定到全局变量环境。
所以建议不要使用new,类继承是代码重用的唯一方式,但是JavaScript有着更多更好的选择。
2 对象说明符(Object Specifiers)
instead of:
var myObject = maker(f, l, m, c, s);
we can write:
var myObject = maker({
first: f,
last: l,
middle: m,
state: s,
city: c
});
3 原型(Prototypal)
差异化继承(differential inheritance.) 通过Object.create 来实现的继承。
代码例:
var myMammal = {
name: 'Herb the Mammal',
get_name: function() {
return this.name;
},
says: function() {
return this.saying || '';
}
};
var myCat = Object.create(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.purr = function(n) {
var i, s = '';
for (i = 0; i < n; i += 1) {
if (s) {
s += '-';
}
s += 'r';
}
return s;
};
myCat.get_name = function() {
return this.says() + ' ' + this.name + ' ' + this.says();
};
4 函数化(Functional)--不太懂,以后再看一遍
上面的例子可以这样实现
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.get_name = function() {
return that.says() + ’’ +spec.name + ’’ +that.says();
};
return that;
};
var myCat = cat({
name: 'Henrietta'
});
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.get_name = function() {
return that.says() + ’’ +spec.name + ’’ +that.says();
};
return that;
};
var myCat = cat({
name: 'Henrietta'
});
5 部件(Parts)
以后再补充。。。