JS中的call、apply、bind方法详解

JS中bind、call和apply的作用以及在TypeScript中装饰器的用法

 

1,前言


bindcallapply在函数式编程时候非常有用,本文旨在记录一下我遇到过的一些用法和知识点,也记录一下在装饰器中的用法。

1,call


call() 方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数。它的第一个参数是你需要指向的this目标,后面的参数是你需要传递的参数,无参数可以不写。

语法:

function.call(target, arg1, arg2, ...)

1.1,例子

如下,控制台会打印出:快看【张三】在奔跑

const Person = {
  Name: '张三',
  Run() {
    return `快看【${this.Name}】在奔跑`
  }
}

const Animal = {
  Name: '猛犸象'
}

console.log(Person.Run()) // 打印出:快看【张三】在奔跑

让我们使用call改变下this指向

1.2,直接调用

如果没有传递第一个参数,this的值将会被绑定为全局对象,也就是window对象(浏览器环境)。由于在window上找不到this.Name这个属性,控制台会打印出:快看【undefined】在奔跑

console.log(Person.Run.call()) // 打印出:快看【undefined】在奔跑

1.3,将this指向另一个对象

此时this会绑定为被指向的对象,控制台会打印出:快看【猛犸象】在奔跑

console.log(Person.Run.call(Animal)) // 打印出:快看【猛犸象】在奔跑

1.4,传递参数

const Person = {
  Name: '张三',
  Run(param1, param2) {
    console.log(param1)
    console.log(param2)
    return `快看【${this.Name}】在奔跑`
  }
}

const Animal = {
  Name: '猛犸象'
}

console.log(Person.Run.call(Animal, 10, '100')) // 打印出:10、'100'、快看【猛犸象】在奔跑

2,apply


apply()方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。它的第一个参数是你需要指向的this目标,后面的参数是你需要传递的数组参数,无参数可以不写。

语法:

function.apply(target, [argsArray])

2.1,例子

如下,控制台会打印出:快看【张三】在奔跑

const Person = {
  Name: '张三',
  Run() {
    return `快看【${this.Name}】在奔跑`
  }
}

const Animal = {
  Name: '猛犸象'
}

console.log(Person.Run()) // 打印出:快看【张三】在奔跑

让我们使用apply改变下this指向

2.2,直接调用

如果没有传递第一个参数,this的值将会被绑定为全局对象,也就是window对象(浏览器环境)。由于在window上找不到this.Name这个属性,控制台会打印出:快看【undefined】在奔跑

console.log(Person.Run.apply()) // 打印出:快看【undefined】在奔跑

2.3,将this指向另一个对象

此时this会绑定为被指向的对象,控制台会打印出:快看【猛犸象】在奔跑

console.log(Person.Run.apply(Animal)) // 打印出:快看【猛犸象】在奔跑

2.4,传递参数

const Person = {
  Name: '张三',
  Run(...arg) {
    console.log(arg)
    return `快看【${this.Name}】在奔跑`
  }
}

const Animal = {
  Name: '猛犸象'
}
console.log(Person.Run.apply(Animal, [10, '100'])) // 打印出:[10、'100']、快看【猛犸象】在奔跑

2.5,合并数组

let arr = ['a', 'b']
let elements = [0, 1, 2]
array.push.apply(arr, elements)
console.log(arr) // ["a", "b", 0, 1, 2]

3,bind


bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

语法:

function.bind(target, arg1, arg2, ...)

3.1,例子

如下,控制台会打印出:快看【张三】在奔跑

const Person = {
  Name: '张三',
  Run() {
    return `快看【${this.Name}】在奔跑`
  }
}

const Animal = {
  Name: '猛犸象'
}

console.log(Person.Run()) // 打印出:快看【张三】在奔跑

让我们使用apply改变下this指向

3.2,直接调用

如果没有传递第一个参数,this的值将会被绑定为全局对象,也就是window对象(浏览器环境)。由于在window上找不到this.Name这个属性,控制台会打印出:快看【undefined】在奔跑

注意:bind返回的是一个方法,需要加上()执行才行

console.log(Person.Run.bind()()) // 打印出:快看【undefined】在奔跑

3.3,将this指向另一个对象

此时this会绑定为被指向的对象,控制台会打印出:快看【猛犸象】在奔跑

console.log(Person.Run.bind(Animal)()) // 打印出:快看【猛犸象】在奔跑

3.4,传递参数

const Person = {
  Name: '张三',
  Run(param1, param2) {
    console.log(param1)
    console.log(param2)
    return `快看【${this.Name}】在奔跑`
  }
}

const Animal = {
  Name: '猛犸象'
}
console.log(Person.Run.bind(Animal, 996, '100')()) // 打印出:996 '100' 快看【猛犸象】在奔跑

4,TypeScript中装饰器使用


使用bind或者apply或者call,可以将方法装饰器中的this指向被装饰的方法,不影响原方法使用的同时,注入新的逻辑处理。

function GetHttp(param: string) {
    return function (target: any, Name: any, desc: any): void {
  	console.log(target) // 原型
        console.log(Name) // 方法名
        console.log(desc) // 方法描述 desc.value即是该方法
        const ev = desc.value
        desc.value = function(): void {
            console.log('我是改写后的function')
            ev.call(this)
        }
    }
}

class HttpGet {
  name: string
  constructor(name: string) {
    this.name = name
  }
  @GetHttp('方法装饰器')
  request(): void {
    console.log(this.name)
  }
}

const HttpObj = new HttpGet('小红')
HttpObj.request()

// 打印出:方法装饰器、我是改写后的function、小红

5,总结


5.1,相同点

  • 都可以通过指定第一个参数,改变this指向
  • 都可以传递参数

5.2,不同点

  • bind返回的是一个函数,需要加上()来执行
  • apply传递参数需要数组的形式

如果看了觉得有帮助的,我是@鹏多多,欢迎 点赞 关注 评论;END


PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦

 

出处:https://www.cnblogs.com/-pdd/p/15587105.html

=======================================================================================

深入理解 call,apply 和 bind

在JavaScript 中,call、apply 和 bind 是 Function 对象自带的三个方法,这三个方法的主要作用是改变函数中的 this 指向,从而可以达到`接花移木`的效果。本文将对这三个方法进行详细的讲解,并列出几个经典应用场景。

1、call(thisArgs [,args...])

该方法可以传递一个thisArgs参数和一个参数列表,thisArgs 指定了函数在运行期的调用者,也就是函数中的 this 对象,而参数列表会被传入调用函数中。thisArgs 的取值有以下四种情况:

  • 不传,或者传null,undefined, 函数中的 this 指向 window 对象
  • 传递另一个函数的函数名,函数中的 this 指向这个函数的引用
  • 传递字符串、数值或布尔类型等基础类型,函数中的 this 指向其对应的包装对象,如 String、Number、Boolean
  • 传递一个对象,函数中的 this 指向这个对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function a(){
    console.log(this); //输出函数a中的this对象
}
function b(){} //定义函数b
 
var obj = {name:'onepixel'}; //定义对象obj
 
a.call(); //window
a.call(null); //window
a.call(undefined);//window
a.call(1); //Number
a.call(''); //String
a.call(true); //Boolean
a.call(b);// function b(){}
a.call(obj); //Object

这是call 的核心功能,它允许你在一个对象上调用该对象没有定义的方法,并且这个方法可以访问该对象中的属性,至于这样做有什么好处,我待会再讲,我们先看一个简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var a = {
 
    name:'onepixel', //定义a的属性
 
    say:function(){ //定义a的方法
        console.log("Hi,I'm function a!");
    }
};
 
function b(name){
    console.log("Post params: "+ name);
    console.log("I'm "+ this.name);
    this.say();
}
 
b.call(a,'test');
>>
Post params: test
I'm onepixel
I'm function a!

当执行b.call 时,字符串`test`作为参数传递给了函数b,由于call的作用,函数b中的this指向了对象a, 因此相当于调用了对象a上的函数b,而实际上a中没有定义b 。

2、apply(thisArgs [,args[]])

apply 和 call 的唯一区别是第二个参数的传递方式不同,apply 的第二个参数必须是一个数组(或者类数组),而 call 允许传递一个参数列表。值得你注意的是,虽然 apply 接收的是一个参数数组,但在传递给调用函数时,却是以参数列表的形式传递,我们看个简单的例子:

1
2
3
4
5
function b(x,y,z){
    console.log(x,y,z);
}
 
b.apply(null,[1,2,3]); // 1 2 3

apply 的这个特性很重要,我们会在下面的应用场景中提到这个特性。

3、bind(thisArgs [,args...])

bind是ES5 新增的一个方法,它的传参和call类似,但又和 call/apply 有着显著的不同,即调用 call 或 apply 都会自动执行对应的函数,而 bind 不会执行对应的函数,只是返回了对函数的引用。粗略一看,bind 似乎比call/apply 要落后一些,那ES5为什么还要引入bind 呢?

其实,ES5引入 bind 的真正目的是为了弥补 call/apply 的不足,由于 call/apply 会对目标函数自动执行,从而导致它无法在事件绑定函数中使用,因为事件绑定函数不需要我们手动执行,它是在事件被触发时由JS 内部自动执行的。而 bind 在实现改变函数 this 的同时又不会自动执行目标函数,因此可以完美的解决上述问题,看一个例子就能明白:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var obj = {name:'onepixel'};
 
/**
 * 给document添加click事件监听,并绑定onClick函数
 * 通过bind方法设置onClick的this为obj,并传递参数p1,p2
 */
document.addEventListener('click',onClick.bind(obj,'p1','p2'),false);
 
//当点击网页时触发并执行
function onClick(a,b){
    console.log(
            this.name, //onepixel
            a, //p1
            //p2
    )
}

当点击网页时,onClick 被触发执行,输出onepixel p1 p2, 说明 onClick 中的 this 被 bind 改变成了obj 对象,为了对 bind 进行深入的理解,我们来看一下 bind 的 polyfill 实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        var args = Array.prototype.slice.call(arguments, 1);
        var fToBind = this// this在这里指向的是目标函数
        var fBind = function () {
            return fToBind.apply(
                // 如果外部执行var obj = new fBind(), 则将obj作为最终的this,放弃使用oThis
                this instanceof fBind
                    ? this  // 此时的 this 就是 new 出的 obj
                    : oThis || this, // 如果传递的 oThis 无效,就将 fBind 的调用者作为this
                // 将通过bind传递的参数和调用时传递的参数进行合并,并作为最终的参数传递
                args.concat(Array.prototype.slice.call(arguments))
            );
        };
 
        // 将目标函数的原型对象拷贝到新函数中,因为目标函数有可能被当作构造函数使用
        fBind.prototype = this.prototype;
 
        // 返回fBind的引用,由外部按需调用
        return fBind;
    };
}          

一旦函数通过bind传递了有效的this对象,则该函数在运行期的this将指向这个对象,即使通过call或apply来试图改变this的指向也是徒劳的。

1
2
3
4
5
6
7
8
9
10
11
var obj1 = {
    name: 'Tom'
}
var obj2 = {
    name: 'Joy' 
}
setTimeout(function() {
    console.log(this.name);
}.bind(obj1).bind(obj2), 0);
 
// Tom

当对一个函数调用多次bind的时候,最终起作用的是第一个bind,这是因为每个bind 都会返回一个闭包 fBind,fBind 里保存了执行目标函数的 scope 和 arguments。执行多次 bind ,目标函数会被多个闭包包装,然后从外到里去执行,当执行真正目标函数的时候,apply 函数中的 scope 和  arguments 读取当前闭包里的变量。   

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 实现数组的去重功能
Array.prototype.unique = function(fn) {
        var rst = [];
        var tmp = {};
        this.forEach(function(val) {
            // 使用call来改变fn的this指向,这里传window
            var key = 'uniq' + (typeof fn === 'function' ? fn.call(window, val) : val);
            if (!tmp.hasOwnProperty(key)) {
                rst.push(val);
                tmp[key] = null;
            }
        }, this);
 
        return rst;
}
 
// 对象数组去重
var arr = [
    { id: 2 }, { id: 4 }, { id: 3 }, { id: 3 }, { id: 4 }, { id: 6 }
]
arr.unique(function(v) {
     console.log(this) // 使用bind传递了Array,则this一定是Array,而不会是window
     return v.id
}.bind(Array));

4、应用场景一:继承

大家知道,JavaScript中没有诸如Java、C# 等高级语言中的extend 关键字,因此JS 中没有继承的概念,如果一定要继承的话,call 和 apply 可以实现这个功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Animal(name,weight){
   this.name = name;
   this.weight = weight;
}
 
function Cat(){
    Animal.call(this,'cat','50');
  //Animal.apply(this,['cat','50']);
 
   this.say = function(){
      console.log("I am " + this.name+",my weight is " + this.weight);
   }
}
 
var cat = new Cat();
cat.say();//I am cat,my weight is 50

当通过new 运算符产生了cat 时,Cat中的 this 就指向了cat对象(关于new运算符的讲解,请参考JS构造函数和new运算符,而继承的关键是在于Cat中执行了Animal.call(this,'cat','50') 这句话,在call中将this作为thisArgs参数传递,于是Animal 方法中的 this 就指向了Cat中的 this,而 cat 中的 this 指向的是 cat 对象,所以Animal 中的 this 指向的就是 cat 对象,在 Animal 中定义了name 和 weight 属性,就相当于在 cat 中定义了这些属性,因此 cat 对象便拥有了Animal 中定义的属性,从而达到了继承的目的。

5、应用场景二:移花接木

在讲下面的内容之前,我们首先来认识一下JavaScript 中的一个非标准专业术语:ArrayLike (类数组/伪数组)

ArrayLike 对象即拥有数组的一部分行为,在DOM 中早已表现出来,而jQuery 的崛起让ArrayLike 在JavaScript 中大放异彩。ArrayLike 对象的精妙在于它和JS 原生的 Array 类似,但是它是自由构建的,它来自开发者对JavaScript 对象的扩展,也就是说:对于它的原型(prototype)我们可以自由定义,而不会污染到JS原生的Array。 

ArrayLike 对象在JS中被广泛使用,比如DOM 中的NodeList, 函数中的arguments 都是类数组对象,这些对象像数组一样存储着每一个元素,但它没有操作数组的方法,而我们可以通过call 将数组的某些方法`移接`到ArrayLike 对象,从而达到操作其元素的目的。比如我们可以这样遍历函数中的arguments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function test(){
    // 检测arguments是否为Array的实例
    console.log(
            arguments instanceof Array, //false
            Array.isArray(arguments)  //false
    );
    // 判断arguments是否有forEach方法
    console.log(arguments.forEach); //undefined
 
    // 将数组中的forEach应用到arguments上
    Array.prototype.forEach.call(arguments,function(item){
        console.log(item); // 1 2 3 4
    });
 
}
test(1,2,3,4);

除此之外,对于apply 而言,我们上面提到了它独有的一个特性,即apply 接收的是数组,在传递给调用函数的时候是以参数列表传递的。 这个特性让apply 看起来比call 略胜一筹,比如有这样一个场景:给定一个数组[1,3,4,7],然后求数组中的最大元素,而我们知道,数组中并没有获取最大值的方法,一般情况下,你需要通过编写代码来实现。而我们知道,Math 对象中有一个获取最大值的方法,即Math.max(), max方法需要传递一个参数列表,然后返回这些参数中的最大值。而apply 不仅可以将Math 对象的max 方法应用到其他对象上,还可以将一个数组转化为参数列表传递给max,看代码就能一目了然:

1
2
3
var arr = [2,3,1,5,4];
 
Math.max.apply(null,arr); // 5

以上便是 call 和 apply 比较经典的几个应用场景,熟练掌握这些技巧,并把这些特性应用到你的实际项目中,会使你的代码看起来更加耐人寻味!

 

原创发布 一像素  博客园 2016.01

 

 

出处:https://www.cnblogs.com/onepixel/p/5143863.html

=======================================================================================

JS中的call、apply、bind方法详解

bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

apply、call

在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向。
JavaScript 的一大特点是,函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。

复制代码
function Fruits() {}
 
Fruits.prototype = {
    color: "red",
    say: function() {
        console.log("My color is " + this.color);
    }
}
 
var apple = new Fruits;
apple.say();    //My color is red
复制代码

但是如果我们有一个对象banana= {color : "yellow"} ,我们不想对它重新定义 say 方法,那么我们可以通过 call 或 apply 用 apple 的 say 方法:

banana = {
    color: "yellow"
}
apple.say.call(banana);     //My color is yellow
apple.say.apply(banana);    //My color is yellow
Fruits.prototype.say.call(banana); //My color is yellow
Fruits.prototype.say.apply(banana); //My color is yellow

所以,可以看出 call 和 apply 是为了动态改变 this 而出现的,当一个 object 没有某个方法(本栗子中banana没有say方法),但是其他的有(本栗子中apple有say方法),我们可以借助call或apply用其它对象的方法来操作。

apply、call 区别

对于 apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。例如,有一个函数定义如下:

var func = function(arg1, arg2) {
     
};

就可以通过如下方式来调用:

func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])

其中 this 是你想指定的上下文,他可以是任何一个 JavaScript 对象(JavaScript 中一切皆对象)。
call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里。  

为了巩固加深记忆,下面列举一些常用用法:

apply、call实例

数组之间追加

var array1 = [12 , "foo" , {name:"Joe"} , -2458]; 
var array2 = ["Doe" , 555 , 100]; 
Array.prototype.push.apply(array1, array2); 
// array1 值为  [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] 

获取数组中的最大值和最小值

var  numbers = [5, 458 , 120 , -215 ]; 
var maxInNumbers = Math.max.apply(Math, numbers),   //458
    maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458

number 本身没有 max 方法,但是 Math 有,我们就可以借助 call 或者 apply 使用其方法。

验证是否是数组(前提是toString()方法没有被重写过)

functionisArray(obj){ 
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

类(伪)数组使用数组方法

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

Javascript中存在一种名为伪数组的对象结构。比较特别的是 arguments 对象,还有像调用 getElementsByTagName , document.childNodes 之类的,它们返回NodeList对象都属于伪数组。不能应用 Array下的 push , pop 等方法。
但是我们能通过 Array.prototype.slice.call 转换为真正的数组的带有 length 属性的对象,这样 domNodes 就可以应用 Array 下的所有方法了。

面试题

定义一个 log 方法,让它可以代理 console.log 方法,常见的解决方法是:

function log(msg) {
  console.log(msg);
}
log(1);    //1
log(1,2);    //1

上面方法可以解决最基本的需求,但是当传入参数的个数是不确定的时候,上面的方法就失效了,这个时候就可以考虑使用 apply 或者 call,注意这里传入多少个参数是不确定的,所以使用apply是最好的,方法如下:

function log(){
  console.log.apply(console, arguments);
};
log(1);    //1
log(1,2);    //1 2

 接下来的要求是给每一个 log 消息添加一个"(app)"的前辍,比如:

log("hello world"); //(app)hello world

该怎么做比较优雅呢?这个时候需要想到arguments参数是个伪数组,通过 Array.prototype.slice.call 转化为标准数组,再使用数组方法unshift,像这样:

function log(){
  var args = Array.prototype.slice.call(arguments);
  args.unshift('(app)');
 
  console.log.apply(console, args);
};

bind

在讨论bind()方法之前我们先来看一道题目:

var altwrite = document.write;
altwrite("hello");

结果:Uncaught TypeError: Illegal invocation
altwrite()函数改变this的指向global或window对象,导致执行时提示非法调用异常,正确的方案就是使用bind()方法:

altwrite.bind(document)("hello")

当然也可以使用call()方法:

altwrite.call(document, "hello")

绑定函数

bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值。常见的错误就像上面的例子一样,将方法从对象中拿出来,然后调用,并且希望this指向原来的对象。如果不做特殊处理,一般会丢失原来的对象。使用bind()方法能够很漂亮的解决这个问题:

复制代码
this.num = 9; 
var mymodule = {
  num: 81,
  getNum: function() { 
    console.log(this.num);
  }
};

mymodule.getNum(); // 81

var getNum = mymodule.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象

var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81
复制代码

bind() 方法与 apply 和 call 很相似,也是可以改变函数体内 this 的指向。

MDN的解释是:bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

直接来看看具体如何使用,在常见的单体模式中,通常我们会使用 _this , that , self 等保存 this ,这样我们可以在改变了上下文之后继续引用到它。 像这样:

复制代码
var foo = {
    bar : 1,
    eventBind: function(){
        var _this = this;
        $('.someClass').on('click',function(event) {
            /* Act on the event */
            console.log(_this.bar);     //1
        });
    }
}
复制代码

由于 Javascript 特有的机制,上下文环境在 eventBind:function(){ } 过渡到 $('.someClass').on('click',function(event) { }) 发生了改变,上述使用变量保存 this 这些方式都是有用的,也没有什么问题。当然使用 bind() 可以更加优雅的解决这个问题:

复制代码
var foo = {
    bar : 1,
    eventBind: function(){
        $('.someClass').on('click',function(event) {
            /* Act on the event */
            console.log(this.bar);      //1
        }.bind(this));
    }
}
复制代码

在上述代码里,bind() 创建了一个函数,当这个click事件绑定在被调用的时候,它的 this 关键词会被设置成被传入的值(这里指调用bind()时传入的参数)。因此,这里我们传入想要的上下文 this(其实就是 foo ),到 bind() 函数中。然后,当回调函数被执行的时候, this 便指向 foo 对象。再来一个简单的栗子:

复制代码
var bar = function(){
console.log(this.x);
}
var foo = {
x:3
}
bar(); //输出 undefined
var func = bar.bind(foo);
func(); // 3
复制代码

这里我们创建了一个新的函数 func,当使用 bind() 创建一个绑定函数之后,它被执行的时候,它的 this 会被设置成 foo , 而不是像我们调用 bar() 时的全局作用域。

部分函数(Partial Functions)

Partial Functions也叫Partial Applications,这里截取一段关于部分函数的定义:

Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.

bind()的另一个最简单的用法是使一个函数拥有预设的初始参数。

只要将这些参数作为bind()的参数写在待绑定对象的后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的前面的开始位置,

传递给绑定函数的参数会跟在这些预设参数的它们后面。

上面说的比较难懂,我们还是来看看实际的示例,你就明白了上面的意思。

复制代码
function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 预定义参数37
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); //这里传递的参数会出现预定义参数的后面: [37, 1, 2, 3]
复制代码

和setTimeout一起使用

复制代码
function Bloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// 1秒后调用declare函数
Bloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 100);
};

Bloomer.prototype.declare = function() {
  console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};

var bloo = new Bloomer();
bloo.bloom(); //我有 5 朵花瓣!
复制代码

注意:对于事件处理函数和setInterval方法也可以使用上面的方法

绑定函数作为构造函数

绑定函数也适用于使用new操作符来构造目标函数的实例。当使用绑定函数来构造实例,注意:this会被忽略,但是传入的参数仍然可用。

复制代码
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function() { 
  console.log( this.name + '==' + this.x + ',' + this.y);
};

var p = new Point(1, 2);
p.toString(); // '1,2'


var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0/*x*/);//方式一: 实现中的例子不支持,
var YAxisPoint = Point.bind(null, 0/*x*/);//方式二:原生bind支持, var axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' console.log(axisPoint instanceof Point); // true console.log(axisPoint instanceof YAxisPoint); // true console.log(new Point(17, 42) instanceof YAxisPoint); // true
复制代码

捷径

bind()也可以为需要特定this值的函数创造捷径。

例如要将一个类数组对象转换为真正的数组,可能的例子如下:

var slice = Array.prototype.slice;

// ...

slice.call(arguments);

如果使用bind()的话,情况变得更简单:

var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);

实现

上面的几个小节可以看出bind()有很多的使用场景,但是bind()函数是在 ECMA-262 第五版才被加入;它可能无法在所有浏览器上运行。这就需要我们自己实现bind()函数了。

首先我们可以通过给目标函数指定作用域来简单实现bind()方法:

Function.prototype.bind = function(context){
  self = this;  //保存this,即调用bind方法的目标函数
  return function(){
      return self.apply(context,arguments);
  };
};

考虑到函数柯里化的情况,我们可以构建一个更加健壮的bind():

复制代码
Function.prototype.bind = function(context){
  var args = Array.prototype.slice.call(arguments, 1),
  self = this;
  return function(){
      var innerArgs = Array.prototype.slice.call(arguments);
      var finalArgs = args.concat(innerArgs);
      return self.apply(context,finalArgs);
  };
};
复制代码

这次的bind()方法可以绑定对象,也支持在绑定的时候传参。

继续,Javascript的函数还可以作为构造函数,那么绑定后的函数用这种方式调用时,情况就比较微妙了,需要涉及到原型链的传递:

复制代码
Function.prototype.bind = function(context){
  var args = Array.prototype.slice(arguments, 1),
  F = function(){},
  self = this,
  bound = function(){
      var innerArgs = Array.prototype.slice.call(arguments);
      var finalArgs = args.concat(innerArgs);
      return self.apply((this instanceof F ? this : context), finalArgs);
  };

  F.prototype = self.prototype;
  bound.prototype = new F();
  return bound;
};
复制代码

这是《JavaScript Web Application》一书中对bind()的实现:通过设置一个中转构造函数F,使绑定后的函数与调用bind()的函数处于同一原型链上,用new操作符调用绑定后的函数,返回的对象也能正常使用instanceof,因此这是最严谨的bind()实现。

对于为了在浏览器中能支持bind()函数,只需要对上述函数稍微修改即可:

复制代码
if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          // this instanceof fBound === true时,说明返回的fBound被当做new的构造函数调用
          return fToBind.apply(this instanceof fBound
                 ? this
                 : oThis,
                 // 获取调用时(fBound)的传参.bind 返回的函数入参往往是这么传递的
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    // 维护原型关系
    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype; 
    }
    // 下行的代码使fBound.prototype是fNOP的实例,因此
    // 返回的fBound若作为new的构造函数,new生成的新对象作为this传入fBound,新对象的__proto__就是fNOP的实例
    fBound.prototype = new fNOP();

    return fBound;
  };
}
复制代码

有个有趣的问题,如果连续 bind() 两次,亦或者是连续 bind() 三次那么输出的值是什么呢?像这样:

复制代码
var bar = function(){
    console.log(this.x);
}
var foo = {
    x:3
}
var sed = {
    x:4
}
var func = bar.bind(foo).bind(sed);
func(); //?
 
var fiv = {
    x:5
}
var func = bar.bind(foo).bind(sed).bind(fiv);
func(); //?
复制代码

答案是,两次都仍将输出 3 ,而非期待中的 4 和 5 。原因是,在Javascript中,多次 bind() 是无效的。更深层次的原因, bind() 的实现,相当于使用函数在内部包了一个 call / apply ,第二次 bind() 相当于再包住第一次 bind() ,故第二次以后的 bind 是无法生效的。

apply、call、bind比较

那么 apply、call、bind 三者相比较,之间又有什么异同呢?何时使用 apply、call,何时使用 bind 呢。简单的一个栗子:

复制代码
var obj = {
    x: 81,
};
 
var foo = {
    getX: function() {
        return this.x;
    }
}
 
console.log(foo.getX.bind(obj)());  //81
console.log(foo.getX.call(obj));    //81
console.log(foo.getX.apply(obj));   //81
复制代码

三个输出的都是81,但是注意看使用 bind() 方法的,他后面多了对括号。

也就是说,区别是,当你希望改变上下文环境之后并非立即执行,而是回调执行的时候,使用 bind() 方法。而 apply/call 则会立即执行函数。

再总结一下:

  • apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
  • apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
  • apply 、 call 、bind 三者都可以利用后续参数传参;
  • bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

bind详细参考地址:《MDN:Function.prototype.bind()》

 

 

出处:https://www.cnblogs.com/moqiutao/p/7371988.html

posted on 2019-12-15 14:52  jack_Meng  阅读(1457)  评论(0编辑  收藏  举报

导航