来讲下apply和call

EcmaScript3给Function的原型定义了两个方法: Function.prototype.apply和Function.prototype.call数组

call和apply的区别: 主要是传参方式的不一样。 apply传入的是数组或类数组。浏览器

var func = function (a,b,c) {
   alert( [a,b,c] );
}

func.apply( null,[1,2,3] ) ;  // 输出[1,2,3]    第一个参数表示函数体内的this指向,null表示指向函数默认的宿主对象,在浏览器里是window, 若是用严格模式下,则会为null

func.call( null, 1,2,3 );  //也是输出 [1,2,3]

var func = function (a,b,c){
   'use strict';
   alert( this === null ); //输出true
}

var func = function (a,b,c){   
   alert( this === null ); //输出false  , this 是 window
}

//实例:借用其余对象的方法
Math.max.apply( null , [1,2,3,4,6,5] );   //6


//改变this的指向
var obj1 = {
   name: 'dongfang'
}
var obj2 = {
   name: 'zeS'
}

window.name = 'abc';

var getName = function(){
   console.log( this.name);
}

getName(); //输出abc
getName.apply(obj1);  //this指向obj1    输出dongfang
getName.apply(obj2);  //this.指向obj2   输出zeS
相关文章
相关标签/搜索