如何在已实现的函数中获取接口名称

时间:2013-04-30 14:26:05

标签: javascript

以下是我用于在javascript中实现界面概念的代码:

function Interface1(ImplementingClass) {
  return {
       implementedFunction : ImplementingClass.implementedFunction
  }
}

function  Interface2(ImplementingClass) {

   return {
      implementedFunction : ImplementingClass.implementedFunction
   }
}

function ImplementingClass() {
 this.implementedFunction = function() {
     // How to get implemented interface name, for 
     // example here interface name should be Interface1???
 }
}


function Test() {
    this.test = function() {
         return new Interface1(new ImplementingClass());
    }
}


var test = new Test();  
test.test().implementedFunction();

问题:如何在已实现的函数中获取接口名称,例如在java中我们使用运算符的实例

if(this instance of Interface) { 
    // Do something  
}

1 个答案:

答案 0 :(得分:3)

不,instanceof无法工作 - 它仅适用于构造函数的prototype对象的原型继承。如果您需要有关界面的信息,则需要将其放在界面对象上:

function Interface(implementingInstance) {
    return {
        interfaceName: "MyInterface",
        implementedFunction : implementingInstance.implementingFunction
    }
}

function ImplementingClass() {
    this.implementingFunction = function() {
        console.log(this.interfaceName);
    }
}
/* maybe helpful:
ImplementingClass.prototype.interfaceName = "noInterface"; // real instance
*/

function Test() {
    this.test = function() {
        return Interface(new ImplementingClass());
    }
}

new Test().test().implementedFunction();
// calls `implementingFunction` on the object with the `interfaceName` property