在javascript中, function里this的指向?
PHP中文网
PHP中文网 2017-04-10 12:47:07
0
3
614

在function 里面有个 this,该function分别用apply()和call()调用,this的指向?

PHP中文网
PHP中文网

认证0级讲师

全部回覆(3)
伊谢尔伦

在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'}
阿神

http://www.css88.com/archives/4431

Peter_Zhu

http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html#this

JavaScript 有一套完全不同于其它语言的对 this 的处理机制。 在五种不同的情况下 ,this 指向的各不相同。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板