Created
May 4, 2012 04:43
-
-
Save vangie/2592085 to your computer and use it in GitHub Desktop.
how to implement this._super in js function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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值而已。