JavaScript学习笔记apply、call、bind用法说明

来源:互联网 发布:数据库开发 编辑:程序博客网 时间:2024/05/21 14:51

首先,在使用call,apply,bind方法时,我们有必要知道这三个方法究竟是来自哪里?为什么可以使用的到这三个方法?

call,apply,bind这三个方法其实都是继承自Function.prototype中的,属于实例方法。

console.log(Function.prototype.hasOwnProperty(‘call’)) //true
console.log(Function.prototype.hasOwnProperty(‘apply’)) //true
console.log(Function.prototype.hasOwnProperty(‘bind’)) //true

上面代码中,都返回了true,表明三种方法都是继承自Function.prototype的。当然,普通的对象,函数,数组都继承了Function.prototype对象中的三个方法,所以这三个方法都可以在对象,数组,函数中使用。

一、首先说一下apply、call、bind的作用
apply 和 call都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向。call 和 apply二者的作用完全一样,只是接受参数的方式不太一样。
bind方法的主要作用就是将函数绑定至某个对象,bind() 方法会创建一个函数,函数体内this对象的值会被绑定到传入bind() 函数的值。即改变函数的上下文对象。
二、apply、call、bind定义
apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
bind方法:
语法:fun.bind(this,[,arg1[, arg2[, [,.argN]]]]])
定义:bind()方法会创建一个新的函数,称为绑定函数,fun方法在this环境下调用,该方法可传入两个参数,第一个参数作为this,第二个及以后的参数则作为函数的参数调用
说明:在EcmaScript5中扩展了叫bind的方法(IE6,7,8不支持)

也可以参考官方文档的解释:apply 、call 、bind

三、使用示例
1、调用函数
Example1

function add(a,b){    alert(a+b);}function sub(a,b){    alert(a-b);}add.call(sub,3,1); //或者 add.apply(sub, [3, 1]); 

这个例子中的意思就是用 sub对象上下文来替换 add对象上下文,add.call(sub,3,1) == add(3,1) ,所以运行结果为:
alert(4); // 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。

Example2

var info = 'tom';function foo(){    //this指向window     var info = 'jerry';    console.log(this.info);  //tom    console.log(this===window)   //true}foo(); foo.call();foo.apply();

2、call和apply可以改变函数中this的指向
Exmaple1

var obj = {        info:'spike'};foo.call(obj);    //这里foo函数里面的this就指向了objfoo.apply(obj);

Example2

 function Animal() {            this.name = "Animal";            this.showName = function () {                alert(this.name);            }        }        function Dog() {            this.name = "Dog";        }        var animal = new Animal();        var dog = new Dog();        animal.showName.apply(dog, []);        animal.showName.call(dog, "");

通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。call 的意思是把 animal 的方法放到dog上执行,原来dog是没有showName() 方法,现在是把animal 的showName()方法放到 dog上来执行,所以this.name 应该是 Dog。
3、实现继承

 function Animal(name) {            this.name = name;            this.showName = function () {                alert(this.name);            }        }        function Dog(name) {            Animal.call(this, name);        }        var dog = new Dog("dog");        dog.showName();

Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么 Dog中不就有Animal的所有属性和方法了吗,Dog对象就能够直接调用Animal的方法以及属性了
4、其他用法
一、合并数组

    var arr1=[1,3,4];    var arr2=[3,4,5];    //自从有了Apply,事情就变得如此简单    Array.prototype.push.apply(arr1,arr2);

二、计算数组中的最大值

var arr = [123,34,5,23,3434,23];//方法一var arr1 = arr.sort(function(a,b){    return b-a;});console.log(arr1[0]);//方法二var max = Math.max.apply(null,arr)   //借用别的对象的方法console.log(max);

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

window.id="window";document.querySelector('#test').onclick = function(){  console.log(this.id);//test  var fun = function(){    console.log(this.id);  }  fun();//window}

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

window.id="window";document.querySelector('#test').onclick = function(){  console.log(this.id);//test  var fun = function(){    console.log(this.id);  }  fun.call(this);//test}

当然你也可以这样做,不过在ECMAScript 5的strict模式下,这种情况下的this已经被规定为不会指向全局对象,而是undefined

window.id="window";document.querySelector('#test').onclick = function(){  var that = this;  console.log(this.id);//test  var fun = function(){    console.log(that.id);  }  fun();//test}function func(){  "use strict"  alert ( this );  // 输出:undefined}func();

6、bind示例

function T(c) {    this.id = "Object";    this.dom = document.getElementById("scroll");}T.prototype = {    init: function() {       //①        this.dom.onmouseover = function() {            console.log("Over-->"+this.id);        }       //②        this.dom.onmouseout = function() {            console.log("Out -->"+this.id);        } .bind(this)    }};(new T()).init();

结果:
这里写图片描述
通过①和②的对照加上显示的结果就会看出bind的作用:改变了上下文的this
bind与call很相似,,例如,可接受的参数都分为两部分,且第一个参数都是作为执行时函数上下文中的this的对象。
不同点有两个:
一、bind的返回值是函数

//都是将obj作为上下文的thisfunction func(name,id) {    console.log(name,id,this);}var obj = "Look here";//什么也不加,直接调用func("    ","-->");//使用bind是 返回改变上下文this后的函数var f = func.bind(obj, "bind", "-->");f();//使用call是 改变上下文this并执行函数var f1 = func.call(obj, "call", "-->");

结果:
这里写图片描述
这里写图片描述

二、后面的参数的使用也有区别

function f(a,b,c){    console.log(a,b,c);}var f_Extend = f.bind(null,"extend_A")f("A","B","C");  //这里会输出--> A,B,Cf_Extend("A","B","C");  //这里会输出--> extend_A,A,Bf_Extend("B","C");  //这里会输出--> extend_A,B,Cf.call(null,"extend_A"); //这里会输出--> extend_A,undefined,undefined

call 是 把第二个及以后的参数作为f方法的实参传进去
而bind 虽说也是获取第二个及以后的参数用于之后方法的执行,但是f_Extend中传入的实参则是在bind中传入参数的基础上往后排的。

var f_Extend = f.bind(null,"extend_A");//等价于如下代码var f_Extend = function(b,c){    return f.call(null,"extend_A",b,c);}

示例二
var eleBtn = document.getElementById(“button”)
, eleText = document.getElementById(“text”);

eleBtn.onclick = function(color) {
color = color || “#003399”;
this.style.color = color;
}.bind(eleText, “#cd0000”);

示例三
举一个应用场景:例如现在有一个方法 根据不同的文件类型进行相应的处理,通过bind 就可以创建出简化版的处理方法
function FileDealFunc(type,url,callback){
if(type==”txt”){…}
else if(type==”xml”){…}
…..
}
var TxtDealFunc = FileDealFunc.bind(this,”txt”);

//这样使用的时候更方便一些
FileDealFunc(“txt”,XXURL,func); //原来
TxtDealFunc(XXURL,func); //现在

四、扩展bind方法,使IE6、IE7、IE8也支持bind方法。

if (!Function.prototype.bind) {    Function.prototype.bind = function(obj) {        var _self = this            ,args = arguments;        return function() {            _self.apply(obj, Array.prototype.slice.call(args, 1));        }    }}

五、bind与call/apply的总结
1:第一个参数都是指定函数内部中this的指向(函数执行时所在的作用域,改变函数执行的上下文环境),然后根据指定的作用域,调用该函数。

  2:都可以在函数调用时传递参数。call,bind方法需要直接传入,而apply方法需要以数组的形式传入。

  3:call,apply方法是在调用之后立即执行函数,而bind方法没有立即执行(一般用在异步调用和事件),需要将函数再执行一遍。有点闭包的味道。

  4:改变this对象的指向问题不仅有call,apply,bind方法,也可以使用that变量来固定this的指向
  
  

原创粉丝点击