是否可以让类在JavaScript中调用函数?
例如:
function Foo(){
this.alertCaller = alertCaller;
}
function Bar(){
this.alertCaller = alertCaller;
}
function alertCaller(){
alert(*calling object*);
}
当调用Foo()。alertCaller()时,我想输出类Foo(),当调用Bar()时,alertCaller()我想outbut Bar()。我有什么方法可以做到这一点吗?
答案 0 :(得分:4)
试试这个:
function alertCaller(){
alert(this.constructor);
}
答案 1 :(得分:2)
我建议你不要做你想做的事。
可能有更好的设计可以满足您的需求。
如果您没有严格模式启用
,则可以使用此功能function alertCaller(){
alert(arguments.callee.caller);
}
答案 2 :(得分:1)
如果我理解你..
function Foo(){
this.alertCaller = alertCaller;
}
function Bar(){
this.alertCaller = alertCaller;
}
Foo.prototype.alertCaller = function() { alert('Foo'); }
Bar.prototype.alertCaller = function() { alert('Bar'); }
foo = new Foo();
foo.alertCaller();
Bar= new Foo();
Bar.alertCaller();