如果我有这样的功能:
function foo(_this) {
console.log(_this);
}
function bar() {}
bar.prototype.func = function() {
foo(this);
}
var test = new bar();
test.func();
然后 bar
的 test
实例被记录。
但是,要使其正常工作,我必须在 bar.prototype.func
函数中传递 this
。我想知道是否有可能获得相同的 this
值而不传递 this
。
我尝试使用 arguments.callee.caller
,但这会返回原型(prototype)函数本身,而不是原型(prototype)函数内的 this
值。
是否可以仅通过在原型(prototype)函数中调用 foo()
来记录 bar
的 test
实例?
最佳答案
如果问题是“没有通过这个(以任何方式)”那么答案是否
不过,值可以通过其他方法传递。例如使用全局变量(在 Bar 类中) 或 session 或 cookie。
function bar() {
var myThis;
function foo() {
console.log(myThis);
}
bar.prototype.func = function() {
myThis = this;
foo();
}
}
var test = new bar();
test.func();
关于javascript - 如何获取调用函数的 'this' 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332017/