如何识别被调用的javascript原型方法';来自另一个原型方法的名称
有两个javascript“对象类”MyClass1和MyClass2,其中MyClass1中的一个方法(foo)调用了MyClass2中的一个方法(moo),我需要动态识别是谁从moo本身调用函数原型moo 当我使用普遍建议的arguments.callee.caller访问器时,我无法派生名称。总的来说,我需要从方法moo知道它是从MyClass1的moo方法或其他方法调用的如何识别被调用的javascript原型方法';来自另一个原型方法的名称,javascript,Javascript,有两个javascript“对象类”MyClass1和MyClass2,其中MyClass1中的一个方法(foo)调用了MyClass2中的一个方法(moo),我需要动态识别是谁从moo本身调用函数原型moo 当我使用普遍建议的arguments.callee.caller访问器时,我无法派生名称。总的来说,我需要从方法moo知道它是从MyClass1的moo方法或其他方法调用的 function MyClass1() { this.myAttribute1 = 123; } MyCl
function MyClass1() {
this.myAttribute1 = 123;
}
MyClass1.prototype.foo = function () {
var myclass2 = new MyClass2();
myclass2.moo();
};
function MyClass2() {
this.mySomething = 123;
}
MyClass2.prototype.moo = function () {
console.log("arguments.callee.caller.name = " +
arguments.callee.caller.name);
console.log("arguments.callee.caller.toString() = " +
arguments.callee.caller.toString());
};
在上面的示例中,arguments.callee.caller.name的结果为空,而调用方的toString()方法显示函数体,但不显示其所有者类或方法名称
之所以需要这样做,是因为我想创建一个调试方法来跟踪从一个方法到另一个方法的调用。我广泛使用对象类和方法。您需要命名函数表达式。试试这个:
function MyClass1() {
this.myAttribute1 = 123;
}
MyClass1.prototype.foo = function foo() { // I named the function foo
var myclass2 = new MyClass2;
myclass2.moo();
};
function MyClass2() {
this.mySomething = 123;
}
MyClass2.prototype.moo = function moo() { // I named the function moo
console.log("arguments.callee.caller.name = " +
arguments.callee.caller.name);
console.log("arguments.callee.caller.toString() = " +
arguments.callee.caller.toString());
};
请参见演示:
问题是您正在将一个没有名称的函数分配给MyClass1.prototype.foo
。因此,它的name
属性是一个空字符串(“”
)。您需要命名函数表达式,而不仅仅是属性
如果要确定
arguments.callee.caller
是否来自MyClass1
,则需要执行以下操作:
var caller = arguments.callee.caller;
if (caller === MyClass1.prototype[caller.name]) {
// caller belongs to MyClass1
} else {
// caller doesn't belong to MyClass1
}
但是请注意,此方法取决于函数的
名称
是否与在MyClass1.prototype
上定义的属性名称相同。如果将名为bar
的函数分配给MyClass1.prototype.foo
,则此方法将不起作用。谢谢。我甚至不知道有可能命名这个方法函数。这么简单。顺便说一句,你知道如何识别调用方(foo)来自类MyClass1吗?@gextra是的,这是可能的。我更新了我的答案,以演示如何。