Skip to content

Instantly share code, notes, and snippets.

@hehongwei44
Created July 11, 2014 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hehongwei44/2f89e61a0e6d4fd722c4 to your computer and use it in GitHub Desktop.
Save hehongwei44/2f89e61a0e6d4fd722c4 to your computer and use it in GitHub Desktop.
JavaScript中的类继承
/**
* 把一个实例方法添加到一个类中
* 这个将会添加一个公共方法到 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;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment