文章出處
文章列表
直接上代碼:
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>
文章列表
全站熱搜