zoukankan      html  css  js  c++  java
  • javascript类式继承函数最优版

    直接上代码:

    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>
  • 相关阅读:
    IOS之UIKit_Day13
    IOS之UIKit_Day12
    IOS之UIKit_Day11
    IOS之UIKit_Day10
    iOS设计模式之工厂模式
    常用操作
    盒子模式
    block循环使用问题
    IOS-sqlite3
    IOS-View用作控制器
  • 原文地址:https://www.cnblogs.com/fengyuqing/p/javascript_extend_fn.html
Copyright © 2011-2022 走看看