Skip to content

Instantly share code, notes, and snippets.

@vangie
Created May 4, 2012 04:43
Show Gist options
  • Save vangie/2592085 to your computer and use it in GitHub Desktop.
Save vangie/2592085 to your computer and use it in GitHub Desktop.
how to implement this._super in js function
// tests if we can get super in .toString()
fnTest = /xyz/.test(function() {
xyz;
}) ? /\b_super\b/ : /.*/,
// overwrites an object with methods, sets up _super
// newProps - new properties
// oldProps - where the old properties might be
// addTo - what we are adding to
inheritProps = function( newProps, oldProps, addTo ) {
addTo = addTo || newProps
for ( var name in newProps ) {
// Check if we're overwriting an existing function
addTo[name] = isFunction(newProps[name]) &&
isFunction(oldProps[name]) &&
fnTest.test(newProps[name]) ? (function( name, fn ) {
return function() {
var tmp = this._super,
ret;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = oldProps[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, newProps[name]) : newProps[name];
}
}
@vangie
Copy link
Author

vangie commented May 4, 2012

1.fnTest 测试 Function.toString 方法是否被覆写,未被覆写的情况下,输出function的源代码。
2.fnTest.test(newProps[name])判断function中是否有this._super调用,如果有着代理该方法,将this._super赋给该方法的父类方法。
3.var tmp = this._super 缓存this._super若子类中定义了this._super,不会生效,以为所有调用this._super的地方都被代理了。this._super = tmp;的作用基本上就是还原this._super的undefined值而已。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment