02_js中接口的定义和使用

来源:互联网 发布:淘宝主图用什么背景 编辑:程序博客网 时间:2024/06/17 03:59

js中接口的定义和使用

 

js中定义和使用接口有三种方式:

1. 通过注释来声明,这个属于文档规范的范畴,需要程序员严格遵守约定。

2. 通过属性声明和检查。使用很少。

3. 通过鸭式辨认来实现接口:某个类是否声明自己支持哪些接口并不重要,只要它具有接口中的这些方法就行。

 

本文演示的是第三种方法。

 

下面是Interface.js的实现:

/**
 *  var Person=new Interface("person",["sayHello","eat"]);
 * @param name
 * @param methods  接口中定义的方法,数组形式
 * @constructor
 */
function Interface(name, methods) {
    if (arguments.length != 2) {
        throw new Error("定义接口参数个数错误!");
    }
    this.name = name;
    this.methods = [];
    for (var 0< methods.lengthi++) {
        if (typeof methods[i] !== "string") {
            throw new Error(this.name "接口中方法定义有误!");
        }
        this.methods.push(methods[i]);
    }
}

/**

 *类的静态方法,用于确认某个类的实例是否实现的给定的接口。
 * Interface.ensureImplements(student,["Person","Learner"]);
 * @param object
 * @param interfaces  接口数组
 */
Interface.ensureImplements function (object, interfaces) {
    if (arguments.length != 2) {
        throw new Error("Interface.ensureImplements方法参数个数错误!");
    }
    if (!(object instanceof Object)) {
        throw new Error("Interface.ensureImplements第一个参数必须为Object实例!");
    }
    if (Object.prototype.toString.call(interfaces) !== "[object Array]") {
        throw new Error("Interface.ensureImplements第二个参数必须为接口数组!");
    }

    for (var 0< interfaces.lengthi++) {
        var interface = interfaces[i];
        if (!(interface instanceof  Interface)) {
            throw new Error("Interface.ensureImplements第二个参数中对象必须为Interface实例");
        }
        for (var 0interface.methods.lengthj++) {
            var method interface.methods[j];
            if (!object[method] || typeof object[method] !== "function") {
                throw new Error("接口中的" method "方法未被实现!");
            }
        }
    }
}

 

 

下面是使用举例:

//定义接口以及接口中的方法
 var Person new Interface("Person", ["sayHello""eat"]);
 var Learner new Interface("Learner", ["learn"]);

 function Student(name) {
     this.name = name;
 }
 Student.prototype.sayHello function () {
     alert("hello");
 };
 Student.prototype.eat function () {
     alert("eat");
 }
 Student.prototype.learn function () {
     alert("I am a learner");
 }

 function test(student) {
     Interface.ensureImplements(student, [PersonLearner]);
     /*
      *确保了student实现了必须的接口之后,就可以放心的调用接口中定义的方法!!!
      */
     student.sayHello();
     student.eat();
     student.learn();
 }

 var stu new Student();
 test(stu);  //调用方法

 

 

0 0