javascript类式继承函数最优版
2013-10-16 22:56
288 查看
直接上代码:
klass函数
使用实例:
klass函数
var klass = function (Parent, props) { var Child, F, i; //1.新构造函数 Child = function () { if (Child.uber && Child.uber.hasOwnProperty("__construct")) { Child.uber.__construct.apply(this, arguments); } if (Child.prototype.hasOwnProperty("__construct")) { Child.prototype.__construct.apply(this, arguments); } }; //2.继承 Parent = Parent || Object; F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.uber = Parent.prototype; Child.prototype.constructor = Child; //3.添加实现方法 for (i in props) { if (props.hasOwnProperty(i)) { Child.prototype[i] = props[i]; } } //返回该class return Child; };
使用实例:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>类式继承</title> <script src="klass.js"></script> </head> <body> <script> var Man = klass(null, { __construct : function (name) { console.log("Man's constructor!"); this.name = name; }, getName : function () { return this.name; } }); //var first = new Man('Adam'); //console.log(first.getName()); var SuperMan = klass(Man, { __construct : function (name) { console.log("SuperMan's constructor!"); }, getName : function () { var name = SuperMan.uber.getName.apply(this); return "I am " + name; } }); var clark = new SuperMan('Clark Kent'); console.log(clark.getName()); </script> </body> </html>
相关文章推荐
- javascript类式继承最优版
- 虚继承和虚函数继承
- C++ 类成员函数继承(virtual、非virtual)
- 虚函数与虚继承
- c++笔记之函数与预处理、类与对象、继承与派生
- 虚函数与虚继承寻踪
- 虚函数、虚继承、sizeof
- 第十周任务二 继承之填充函数
- Visual C++ 8.0对象布局的奥秘:虚函数、多继承、虚拟继承
- C++继承中子类未定义函数的局限性
- scala 函数参数 变长参数 类继承测试
- 虚函数、虚继承
- C++中虚函数和非虚函数重载在继承时的区别
- C++内存分布之菱形继承(无虚函数)
- php protected只能被继承,不可以在实例中调用,parent::调用父类(子类函数的重载对父类的函数没有影响)
- javascript继承之工具函数一
- java类继承中父类调用子类函数的问题
- C++中虚函数工作原理和(虚)继承类的内存占用大小计算
- (继承及其访问限定符)&&(派生类及其默认成员函数)&&(赋值兼容规则)
- javaScript 中 call 函数的用法说明 & 继承