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
  • 相关阅读:
    27. Remove Element
    列表变成字典
    1. Two Sum
    CVPR2019:What and How Well You Performed? A Multitask Learning Approach to Action Quality Assessment
    959. Regions Cut By Slashes
    118. Pascal's Triangle
    loj3117 IOI2017 接线 wiring 题解
    题解 NOI2019 序列
    题解 省选联考2020 组合数问题
    题解 Educational Codeforces Round 90 (Rated for Div. 2) (CF1373)
  • 原文地址:https://www.cnblogs.com/king2016/p/5968037.html
Copyright © 2011-2022 走看看