[英]How to detect where the function is called from in Javascript
我有这个代码
var Test = function(){
this.prefix = function(prefix, callback){
callback.call({pre: prefix})
}
this.log = function(stuff){
console.log(this.pre, stuff);
}
}
var tester = new Test();
tester.log('a'); // should log 'a' -> logs undefined, 'a'
tester.prefix('b', function(){
console.log(this.pre) // -> logs 'b'
tester.log('c'); // should log 'bc' -> logs undefined, 'c'
})
tester.log('d'); // should log 'd' -> logs undefined, 'd'
基本上,当我在前缀回调中运行 tester.log 时,它应该以前缀记录输出。 我知道我可以在回调函数中传递一个带有预定义前缀的新测试器对象作为参数。 但是我可以在没有参数的情况下做到这一点吗?
您需要在 Test 对象上设置 pre:
var Test = function(){
this.prefix = function(prefix, callback){
this.pre = prefix;
callback.call({pre: prefix})
}
this.log = function(stuff){
console.log(this.pre, stuff);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.