js鴨式辨型

1.鴨式辨型的核心監(jiān)測接口里的方法是否被實現(xiàn)類都實現(xiàn)

<script type="application/javascript">

    /**
     * 定義接口類
     * @param name  接口名稱
     * @param methods   方法數(shù)組
     * @constructor
     */
    var Interface = function (name, methods) {
        if (arguments.length != 2) {
            return;
        }
        this.name = name;
        this.methods = [];
        for (var i = 0, len = methods.length; i < len; i++) {
            if (typeof methods[i] != 'string') {
                return;
            }
            this.methods.push(methods[i]);
        }
    };

    /**
     * 實現(xiàn)類
     */
    var MyInterfaceImpl = function () {

    };

    MyInterfaceImpl.prototype.setName = function (name) {
        this.name = name;
        console.log(name);
    };

    MyInterfaceImpl.prototype.getName = function () {
        console.log(this.name);
    };
    
    /**
     * 檢測接口里面的方法
     * @param obj
     */
    Interface.ensureImplements = function (obj) {
        if (arguments.length < 2) {
            throw new Error('最少傳遞兩個參數(shù)');
        }
        // 獲取接口實現(xiàn)方法
        for (var i = 1; i < arguments.length; i++) {
            var instanceInterface = arguments[i];
            if (instanceInterface.constructor != Interface) {
                return;
            }
            // 循環(huán)接口的每個方法
            for (var j = 0, len = instanceInterface.methods.length; j < len; j++) {
                var methodName = instanceInterface.methods[j];
                if (!obj[methodName] || typeof obj[methodName] != 'function') {
                    return;
                }
            }
        }
    };

    var c1 = new MyInterfaceImpl('MyInterfaceImpl', ['setName', 'getName']);
    c1.setName('測試');
    c1.getName();
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容