下面是我用来在 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();
问题:如何在实现的函数中获取接口(interface)名称,例如在java中我们使用运算符实例
if(this instance of Interface) {
// Do something
}
最佳答案
不,instanceof
不起作用 - 它仅适用于从构造函数的 prototype
对象进行原型(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
关于javascript - 如何在实现的函数中获取接口(interface)名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16302298/