javascript Function.call中的this指向问题
本文介绍了javascript Function.call中的this指向问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
已知如下代码:
var foo = 1;
var bar = 10;
function a (arg, func) {
this.foo = arg + this.bar;
func(this.foo);
}
var b = {
foo: 100,
bar: 1000
};
a.call(b, 10000, function(x) {
console.log(this.foo + x);
});
问: 该代码执行后控制台打印结果是什么?分析产生该结果的原因。
我本来以为执行结果会是22000,因为直接把call中的参数带入函数a后是:
function a (arg, func) {
this.foo = arg + this.bar;
console.log(this.foo + this.foo);
}
然后由于arg = 10000,b.foo = arg + b.bar = 10000 + 1000 = 11000,11000 + 11000 = 22000.
但是执行结果却是11001,也就是说console.log
里的this
指向的是window
,对此我表示不解,既然这个function是作为a
的参数带入的,既然a
的this
被指向了b
,为什么这里的this
不会指向b
呢?希望各位高手解惑。另外,如果这个this
不指向b
,有没有什么方法在仍使用this.foo
的情况下将这个this
指向b
?
解决方案
function a (arg, func) {
this.foo = arg + this.bar;
(func.bind(this))(this.foo);
}
这篇关于javascript Function.call中的this指向问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文