name327 发表于 2013-1-29 08:41:56

js的继承工具函数

来自于这里,http://javascript.crockford.com/inheritance.html
这个可以为javascript继承提供很大的方便
目前还不知道有没有什么弊端
 
Function.prototype.method=function(name,fun){ this.prototype=fun; return this; } Function.method('inherits', function (parent) {    var d = {}, p = (this.prototype = new parent());    //这个方法可以用来调用被覆盖的父类方法    this.method('uber', function uber(name) {      if (!(name in d)) {            d = 0;      }                var f;//要执行的函数      var r;//函数的返回值      var t = d, v = parent.prototype;      if (t) {            while (t) {                v = v.constructor.prototype;                t -= 1;            }            f = v;      } else {            f = p;            if (f == this) {                f = v;            }      }      d += 1;      r = f.apply(this, Array.prototype.slice.apply(arguments,));      d -= 1;      return r;    });    return this;}); function Person(name){ this.name=name; } //给Person添加getName Person.method("getName", function(o){return this.name; }); function User(name,password){ this.name=name; this.password=password; }; //User继承Person User.inherits(Person); User.method("getPassword",function(){ alert(this.password); }); //重写getName方法 User.method("getName",function(o){ //this.uber("getName")调用原始的getName方法,如果原始方法带参数则为this.uber("method",arg1,arg2,argN) alert("My Name is "+this.uber("getName")); }); var u=new User("张三",111111); u.getPassword(); u.getName(); 如果有什么不对的 欢迎指出,
页: [1]
查看完整版本: js的继承工具函数