/**
* 把一个实例方法添加到一个类中
* 这个将会添加一个公共方法到 Function.prototype中,
* 这样通过类扩展所有的函数都可以用它了。它要一个名称和一个函数作为参数。
* 它返回 this。当我写一个没有返回值的方法时,我通常都会让它返回this。
* 这样可以形成链式语句。
*
* */
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
/**
* 它会指出一个类是继承自另一个类的。
* 它必须在两个类都定义完了之后才能定义,但要在方法继承之前调用。
*
* */
Function.method('inherits', function (parent) {
var d = 0, p = (this.prototype = new parent());
this.method('uber', function uber(name) {
var f, r, t = d, v = parent.prototype;
if (t) {
while (t) {
v = v.constructor.prototype;
t -= 1;
}
f = v[name];
} else {
f = p[name];
if (f == this[name]) {
f = v[name];
}
}
d += 1;
r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
d -= 1;
return r;
});
return this;
});
/**
*
* The swiss方法对每个参数进行循环。每个名称,
* 它都将parent的原型中的成员复制下来到新的类的prototype中
*
* */
Function.method('swiss', function (parent) {
for (var i = 1; i < arguments.length; i += 1) {
var name = arguments[i];
this.prototype[name] = parent.prototype[name];
}
return this;
});
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/10043.html