0

Below is the code I have used to achieve interface concept in 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();

Question: How to get interface name in implemented function, for example in java we use instance of operator

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

1 回答 1

4

不,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
于 2013-04-30T14:33:28.457 回答