dojo中类的继承

        类似于c# java等后台语言,在基于类的面向对象编程中,通常需要在子类中扩展某些父类的方法,这时可以在子类的方法中,先调用从父类继承的方法,然后再执行子类自定义的操作。凡是使用declare创建的类,可以使用一个特殊的inherited方法,在子类中调用父类中被覆盖的方法,也就是说,当在子类中的任何方法中调用this.inherited时,将调用父类中的同名方法。

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var dojoConfig = {
            async: true,
            packages: [{
                name: "js",
                location: location.pathname.replace(/\/[^/]*$/, '') + '/js'
            }]
        };
    </script>
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"
            data-dojo-config="async: true"></script>
    <script>
        require(["js/B"], function (B) {
            var x = new B();
            dojo.safeMixin(x, {
                m1: function () {
                    this.inherited(arguments);
                    console.log("X.m1");
                },
                m2: function () {
                    //凡是使用declare创建的类 可以使用一个特殊的inherited方法,在子类中调用父类中被覆盖的方法,也就是说,当在子类中的任何方法中调用this.inherited时,将调用父类中的同名方法
                    debugger;
                    this.inherited(arguments);
                    console.log("X.m2");
                }
            });
            document.getElementById("btn").onclick=function () {
                x.m2();
            }
        });
    </script>
</head>
<body>
<button id="btn">点击</button>
</body>
</html>

A.js类:

define([
    "dojo/_base/declare"
], function (declare) {
    var A = declare(null, {
        m1: function () {
            console.log("A.m1");
        },
        m2: function () {
            debugger;
            console.log("A.m2");
        }
    });
    return A;
});

B.js类:

define([
    "js/A",
    "dojo/_base/declare"
], function (A,declare) {
    var B = declare(A, {
        m1: function () {
            this.inherited(arguments);
            console.log("B.m1");
        }
    });
    B.extend({
        m2: function () {
            debugger;
            this.inherited(arguments);
            console.log("B.m2");
        }
    });
    return B;
});

结果:

A.m2
B.m2
X.m2

该例中同时也使用了safeMixin方法:

猜你喜欢

转载自www.cnblogs.com/qicao/p/9451436.html