Javascript 如何在实现的函数中获取接口名
下面是我用来在javascript中实现接口概念的代码:Javascript 如何在实现的函数中获取接口名,javascript,Javascript,下面是我用来在javascript中实现接口概念的代码: function Interface1(ImplementingClass) { return { implementedFunction : ImplementingClass.implementedFunction } } function Interface2(ImplementingClass) { return { implementedFunction : Implementing
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
}
不,不起作用-它只适用于从构造函数的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
不,不起作用-它只适用于从构造函数的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
你是说
的instanceof
?我尝试过instanceof操作符,但如果我们实现多个接口,它就不起作用。JavaScript不是一种经典语言,所以像接口和类这样的概念不会直接转换。尽管如此,这些概念中的许多仍然可以被模拟。只是要明确一点:你不能实例化一个接口,你要实例化实现这个接口的对象。要在对象本身中引用此实例,可以使用键工作“this”,您的意思是instanceof
?我尝试过instanceof操作符,但如果我们实现多个接口,它就不起作用。JavaScript不是一种经典语言,所以像接口和类这样的概念不会直接转换。尽管如此,这些概念中的许多仍然可以被模拟。只是要明确一点:你不能实例化一个接口,你要实例化实现这个接口的对象。要在对象本身内部引用此实例,可以使用keywork“this”