如何从函数内部访问函数名?
// parasitic inheritance
var ns.parent.child = function() {
var parent = new ns.parent();
parent.newFunc = function() {
}
return parent;
}
var ns.parent = function() {
// at this point, i want to know who the child is that called the parent
// ie
}
var obj = new ns.parent.child();
可以使用name属性获取函数名,除非使用匿名函数
例如:
var Person = function Person () {
this.someMethod = function () {};
};
Person.prototype.getSomeMethodName = function () {
return this.someMethod.name;
};
var p = new Person();
// will return "", because someMethod is assigned with anonymous function
console.log(p.getSomeMethodName());
现在让我们试试named function
var Person = function Person () {
this.someMethod = function someMethod() {};
};
现在你可以使用
// will return "someMethod"
p.getSomeMethodName()
这可能对你有用:
function foo() { bar(); }
function bar() { console.log(bar.caller.name); }
如果从匿名函数调用,运行foo()将输出“foo”或未定义。
它也适用于构造函数,在这种情况下,它将输出调用构造函数的名称(例如“Foo”)。
更多信息请访问:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller
他们声称这是不标准的,但所有主流浏览器都支持它:Firefox、Safari、Chrome、Opera和IE。