在javascript设计模式里面讲到代码的灵活性,下面两种编码风格我很喜欢,第一种使用原型并赋予其原型一个函数作为参数.这里面使用this.prototype[name]相当于给原型一个数组引用:
/ Add a method to the Function class that can be used to declare methods. /
Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
};
/ Anim class, with methods created using a convenience method. /
var Anim = function() {
…
};
Anim.method(‘start’, function() {
…
});
Anim.method(‘stop’, function() {
…
});
而第二种则在第一种基础上返回this,并让添加函数方法可以做链式调用:
/ This version allows the calls to be chained. /
Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
return this;
};
/ Anim class, with methods created using a convenience method and chaining. /
var Anim = function() {
…
};
Anim.
method(‘start’, function() {
…
}).
method(‘stop’, function() {
…
});