JavaScript中call和apply方法的使用

acvaScript中的call()方法和apply()方法,在某些时候这两个方法还确实是十分重要的。
1. 每个函数都包含两个非继承而来的方法:call()方法和apply()方法。
2. 相同点:这两个方法的作用是一样的。
都是在特定的作用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的作用域。
一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。

call()方法使用示例:

 1 //例一
 2   window.color = 'red';
 3   document.color = 'yellow';
 4   var s1 = { color: 'blue' };
 5   function changeColor() {
 6     console.log(this.color);
 7   }
 8   changeColor.call(); //red (默认传递参数) 
 9   changeColor.call(window); //red
10   changeColor.call(document); //yellow 
11   changeColor.call(this); //red 
12   changeColor.call(s1); //blue
 1 //例二
 2  var Pet = {
 3     words : '...', 
 4     speak : function (say) {
 5        console.log(say + ''+ this.words) 
 6        } 
 7   }
 8   Pet.speak('Speak'); // 结果:Speak... 
 9   var Dog = { words:'Wang' } //将this的指向改变成了Dog 
10   Pet.speak.call(Dog, 'Speak'); //结果: SpeakWang

apply()方法使用示例:

 1 //例一
 2  window.number = 'one';
 3  document.number = 'two'; 
 4  var s1 = {number: 'three' }; 
 5  function changeColor(){ 
 6    console.log(this.number); 
 7  } changeColor.apply(); //one (默认传参) 
 8  changeColor.apply(window); //one 
 9  changeColor.apply(document); //two 
10  changeColor.apply(this); //one
11  changeColor.apply(s1); //three
 1  //例2 
 2  function Pet(words){ 
 3    this.words = words; 
 4    this.speak = function () { 
 5       console.log( this.words) 
 6    } 
 7 } 
 8 function Dog(words){ 
 9    //Pet.call(this, words); //结果: Wang 
10    Pet.apply(this, arguments); //结果: Wang 
11 } 
12 var dog = new Dog('Wang');
13  dog.speak();

3. 不同点:接收参数的方式不同。
1.apply()方法 接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。

语法:apply([thisObj [,argArray] ]);,调用一个对象的一个方法,另一个对象替换当前对象。

说明:如果argArray不是一个有效数组或不是arguments对象,那么将导致一个
TypeError,如果没有提供argArray和thisObj任何一个参数,那么Global对象将用作thisObj。

2.call()方法 第一个参数和apply()方法的一样,但是传递给函数的参数必须列举出来。

语法:call([thisObject[,arg1 [,arg2 [,...,argn]]]]);,应用某一对象的一个方法,用另一个对象替换当前对象。

说明: call方法可以用来代替另一个对象调用一个方法,call方法可以将一个函数的对象上下文从初始的上下文改变为thisObj指定的新对象,如果没有提供thisObj参数,那么Global对象被用于thisObj。

1 //例一
2 function add(c,d){ 
3    return this.a + this.b + c + d; 
4 } 
5 var s = {a:1, b:2}; 
6 console.log(add.call(s,3,4)); // 1+2+3+4 = 10 
7 console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14 
 1 //例二
 2  window.firstName = "Cynthia";
 3  window.lastName = "_xie"; 
 4  var myObject = {firstName:'my', lastName:'Object'}; 
 5  function getName(){ 
 6     console.log(this.firstName + this.lastName); 
 7 } 
 8 function getMessage(sex,age){
 9     console.log(this.firstName + this.lastName + " 性别: " + sex + " age: " + age ); 
10 } 
11 getName.call(window); // Cynthia_xie 
12 getName.call(myObject); // myObject 
13 getName.apply(window); // Cynthia_xie 
14 getName.apply(myObject);// myObject 
15 getMessage.call(window,"女",21); //Cynthia_xie 性别: 女 age: 21 
16 getMessage.apply(window,["女",21]); // Cynthia_xie 性别: 女 age: 21 
17 getMessage.call(myObject,"未知",22); //myObject 性别: 未知 age: 22 
18 getMessage.apply(myObject,["未知",22]); // myObject 性别: 未知 age: 22

在实际开发中,经常会遇到this指向被不经意改变的场景。
有一个局部的fun方法,fun被作为普通函数调用时,fun内部的this指向了window,但我们往往是想让它指向该#test节点,见如下代码:

1 window.id="window";
2 document.querySelector('#test').onclick = function(){
3   console.log(this.id);//test
4   var fun = function(){
5     console.log(this.id);
6   }
7   fun();//window
8 }

使用call,apply我们就可以轻松的解决这种问题了

1 window.id="window";
2 document.querySelector('#test').onclick = function(){
3   console.log(this.id);//test
4   var fun = function(){
5     console.log(this.id);
6   }
7   fun.call(this);//test
8 }

还可以有这样的方法:

1 window.id="window";
2 document.querySelector('#test').onclick = function(){
3   var that = this;
4   console.log(this.id);//test
5   var fun = function(){
6     console.log(that.id);
7   }
8   fun();//test
9 }

不过在ES5的严格模式下,this的指向不被规定为全局对象,而是undefined。

1 function func(){
2   "use strict"
3   alert ( this );  // 输出:undefined
4 }
5 func();

call和apply方法还有其他用法

类数组

这里把符合以下条件的对象称为类数组

1.具有length属性

2.按索引方式存储数据

3.不具有数组的push,pop等方法

常见类数组有 arguments,NodeList!

1 (function(){
2   Array.prototype.push.call(arguments,4);
3   console.log(arguments);//[1, 2, 3, 4]
4 })(1,2,3)

这样就往arguments中push一个4进去了

Array.prototype.push 页可以实现两个数组合并

同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来装换一下这个数组,即:

1 var arr1=new Array("1","2","3"); 
2 var arr2=new Array("4","5","6"); 
3 Array.prototype.push.apply(arr1,arr2); 
4 console.log(arr1);//["1", "2", "3", "4", "5", "6"]

也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合.

再比如我想求类数组中的最大值

1 (function(){
2   var maxNum = Math.max.apply(null,arguments);
3   console.log(maxNum);//56
4 })(34,2,56);

还可以判断数据类型:

1 console.log(Object.prototype.toString.call(123)) //[object Number]
2 console.log(Object.prototype.toString.call('123')) //[object String]
3 console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
4 console.log(Object.prototype.toString.call(true)) //[object Boolean]
5 console.log(Object.prototype.toString.call({})) //[object Object]
6 console.log(Object.prototype.toString.call([])) //[object Array]
7 console.log(Object.prototype.toString.call(function(){})) //[object Function]



猜你喜欢

转载自www.cnblogs.com/lcr-smg/p/10067398.html
今日推荐