浏览 356 次
|
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
|---|---|
| 作者 | 正文 |
|
最后更新时间:2008-06-08
jQuery作者John Resig提出了他的继承方案,让人眼前一亮的是能够支持类似Super的关键字调用父类方法。
由于比较习惯YUI/EXT继承方式,同时也了解这种方式的不足,看到John的方案,很想跃然一试, 但见其代码之复杂,思路之繁复,恐怕不能兼效率之(ext中多达7~8层的继承),抱着FUD的心态,望诸君评论之。
1. // Inspired by base2 and Prototype
2. (function(){
3. var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
4.
5. // The base Class implementation (does nothing)
6. this.Class = function(){};
7.
8. // Create a new Class that inherits from this class
9. Class.extend = function(prop) {
10. var _super = this.prototype;
11.
12. // Instantiate a base class (but only create the instance,
13. // don't run the init constructor)
14. initializing = true;
15. var prototype = new this();
16. initializing = false;
17.
18. // Copy the properties over onto the new prototype
19. for (var name in prop) {
20. // Check if we're overwriting an existing function
21. prototype[name] = typeof prop[name] == "function" &&
22. typeof _super[name] == "function" && fnTest.test(prop[name]) ?
23. (function(name, fn){
24. return function() {
25. var tmp = this._super;
26.
27. // Add a new ._super() method that is the same method
28. // but on the super-class
29. this._super = _super[name];
30.
31. // The method only need to be bound temporarily, so we
32. // remove it when we're done executing
33. var ret = fn.apply(this, arguments);
34. this._super = tmp;
35.
36. return ret;
37. };
38. })(name, prop[name]) :
39. prop[name];
40. }
41.
42. // The dummy class constructor
43. function Class() {
44. // All construction is actually done in the init method
45. if ( !initializing && this.init )
46. this.init.apply(this, arguments);
47. }
48.
49. // Populate our constructed prototype object
50. Class.prototype = prototype;
51.
52. // Enforce the constructor to be what we expect
53. Class.constructor = Class;
54.
55. // And make this class extendable
56. Class.extend = arguments.callee;
57.
58. return Class;
59. };
60. })();
声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |



