Maison > Questions et réponses > le corps du texte
在function 里面有个 this,该function分别用apply()和call()调用,this的指向?
伊谢尔伦2017-04-10 12:49:07
在js中,调用function的apply()或者call()可以覆盖this原先的指向。但是call()和apply()的用法略有不同,见下面两个例子:
var myObject = {};
var myFunction = function(param1, param2) {
this.foo = param1;
this.bar = param2;
console.log(this);
};
myFunction.call(myObject, 'foo', 'bar'); // this 将指向 myObject
console.log(myObject) // 输出 Object {foo = 'foo', bar = 'bar'}
用apply()时,参数需要用Array
var myObject = {};
var myFunction = function(param1, param2) {
this.foo=param1;
this.bar=param2;
console.log(this);
};
myFunction.apply(myObject, ['foo', 'bar']); // this 将指向 myObject
console.log(myObject); // 输出 Object {foo = 'foo', bar = 'bar'}
天蓬老师2017-04-10 12:49:07
http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html#this
JavaScript 有一套完全不同于其它语言的对 this 的处理机制。 在五种不同的情况下 ,this 指向的各不相同。