zoukankan      html  css  js  c++  java
  • js面向对象类式继承

    //待研究


    //
    类式继承 //js中模拟类式继承的3个函数 //简单的辅助函数,让你可以将新函数绑定到对象的 prototype 上 Function.prototype.method = function( name, func ){ this.prototype[name] = func; return this; }; //一个(相当复杂的)函数, 允许你方便的从其他对象继承函数, //同时仍然可以调用属于父对象的那些函数 Function.method('inherits', function (parent) { //记录我们目前所在父层次的级数 var depth = 0; //继承父对象的方法 var proto = this.prototype = new parent(); //创建一个新的名为 'uber' 的"特权"函数, //调用它时会执行所有在继承时被重写的函数 this.method('uber', function uber (name) { var func; //要执行的函数 var ret; //函数的返回值 var v = parent.prototype; //父对象的 prototype // 如果我们已经在某个'uber'函数之内 console.log(depth); if (depth) { //上溯必要的depth,以找到原始的 prototype for (var i = 0; i < depth; i++) { v = v.constructor.prototype; } //从该 prototype 中获得函数 func = v[name]; //否则这就是 'uber' 函数的第一次调用 } else { //从 prototype 获得要执行的函数 func = proto[name]; //如果此函数属于当前的 prototype if ( func == this[name]) { // 则改为调用父对象的 prototype func = v[name]; } } //记录我们在继承堆栈中所在位置的级数 depth += 1; //使用除第一个以外所有的 arguments 调用此函数 //(因为第一个参数是执行的函数名) ret = func.apply(this, Array.prototype.slice.apply(arguments,[1])); //恢复继承堆栈 depth -= 1; //返回执行过的函数的返回值 return ret; }); return this; }); //只继承父对象特定函数的函数. 而非使用 new parent() 继承所有的函数 Function.method('swiss',function (parent) { //遍历所有要继承的方法 for (var i = 0; i < arguments.length; i++) { //需要导入的方法名 var name = arguments[i]; //将此方法导入 this 对象的 prototype 中 this.prototype[name] = parent.prototype[name]; } return this; }); //创建一个新的 Person 对象构造函数 function Person ( name ) { this.name = name; } //给 Person 对象添加一个新方法 Person.method('getName',function(){ return this.name; }); //创建一个新的 User 对象构造函数 function User ( name,password ) { this.name = name; this.password = password; } //从 Person 对象继承所有方法 User.inherits( Person ); //给User对象添加一个新的方法 User.method('getPassword',function () { return this.password; }); //覆盖 Person 对象创建的 getName 方法,但通过 uber 函数来调用原有方法 User.method('getName',function () { return "User|| " + this.uber('getName'); }); var user=new User(); function UUser( name,password,age ) { this.name = name; this.password = password; this.age = age; } UUser.inherits( User ); UUser.method('getAge',function () { return this.age; }); UUser.method('getName',function () { return "UUser||" + this.uber('getName'); }); var user2=new UUser( 'xiaohong','pass',50 ); console.log(user2.getName()); //UUser||User|| xiaohong
  • 相关阅读:
    拍拍帐号信息查询PHP
    如何成为“一分钟经理人”?
    性能计数器注册表配置单元一致性失败(Performance counter registry hive consistency check failed )解决方案
    换个心境搞IT在IT职场如何打拼?
    变形金刚3 ——结尾擎天柱经典独白
    修改织梦(DEDE)的上一篇下一篇功能
    android 选择系统自带铃声和选择自定义铃声
    android开发常用方法
    输入特定年月返回该月的天数
    “心”字诀
  • 原文地址:https://www.cnblogs.com/king2016/p/5968037.html
Copyright © 2011-2022 走看看