美文网首页
讲解call() apply() bind()方法

讲解call() apply() bind()方法

作者: ZGC_JO | 来源:发表于2019-03-12 16:23 被阅读0次

在javaScript中,每个函数实际上都是一个Function对象。call、apply和bind就是Function自带的方法。下面对这三个方法进行讲解。

1. fun.call(thisArg, arg1, arg2, ...)

    参数:

        thisArg: 在fun函数运行时指定的this值。但是this值不一定是该函数执行时真正的this值,如果处于非严格模式(non-strict mode), 则指定null和undefined的this值会自动指向全局对象(浏览器中是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。

        arg1, arg2, .... :  指定的参数列表。

说明:call()允许为不同的对象分配和调用属于一个对象的函数/方法。提供新的this值给当前调用的函数/方法。可以使用call来实现继承。

示例:

使用call方法调用父构造函数:

    在子构造函数中,通过调用父构造函数的call方法来实现继承,下例中,Food和Toy构造函数创建的对象都会拥     有在Product构造函数中添加的name属性和price属性,而category属性是在各自的构造函数中定义的。

function Product(name, price){

    this.name = name;

    this.price = price;

}

function Food(name, price){

    Product.call(this, name, price);

    this.category = 'food';

}

function Toy(name, price){

    Product.call(this, name, price);

    this.category = 'toy';

}

var cheese = new Food('feta', 5);

console.log(cheese.name); // 输出:feta

var fun = new Toy('robot', 40);

console.log(fun.name); // 输出:robot

使用call方法调用匿名函数:

    在下例的for循环中构造一个匿名函数,通过调用匿名函数的call方法,将每个数字元素作为指定的this值执行了     匿名函数

const animals = [

    { species: 'Lion', name: 'King' },

    { species: 'Whale', name: 'Fail' }

];

for(let i = 0; i < animals.length; i++){

    (function(){

        this.print = function() {

            console.log('#' + i + ' ' + this.species + ': ' + this.name);

         }

    }).call(animals[i], i);

}

执行上述代码将输出:

#0 Lion: King

#1 Whale: Fail

使用call方法调用函数并确定上下文的this:

    下例中调用greet方法时,改方法的this值会绑定到obj对象。

function greet(){

    const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');

    console.log(reply);

}

const obj = {

    animal: 'cats', sleepDuration: '12 and 16 hours'

}

greet.call(obj);

输出结果为:cats typically sleep between 12 and 16 hours

call方法调用函数并且没有确定第一个参数:

下例中调用display方法,但是没有传递它的第一个参数。如果没有传递第一个参数,this的值将会被绑定为全局对象

const sData = 'Wisen';

function display(){

    console.log('sData value is %s ', this.sData);

}

display.call();

将输出:sData value is Wisen

注意:在严格模式下this的值会是undefined.

2. func.apply(thisArg, [argsArray])

参数:

    thisArg: func函数运行时使用的this值,this可能不是改方法看到的实际值,如何处于非严格模式下,则指定为null或undefined时会自动替换为指向全局对象,原始值会被包装。

    argsArray: 一个数组或类数组对象,数组元素将作为单独的参数传给func函数。如果该参数值为null或undefined,则表示不需要传入任何参数

说明:

    调用一个存在的函数时,为其指定一个this对象。this指向当前对象,也就是正在调用这个函数的对象。使用apply可以只写一次这个方法然后在另一个对象中继承它,而不用在新对象中重复写改方法。

示例:

    用apply将数组添加到另一个数组中:

    const array = ['a', 'b'];

    const elements = [0, 1, 2];

    array.push.apply(array, elements);

    console.log(array);    // ["a", "b", 0, 1, 2]

    使用apply和内置函数

    const numbers = [5, 6, 2, 3, 7];

    // 应用(apply) Math.min/Math.max 内置函数完成

    const max = Math.max.apply(null, numbers);    // 基本等同于Math.max(numbers[0], ...)或Math.max(5,6...)

    const min = Math.min.apply(null, numbers);

    注意:如果用上面的方式调用apply,会有超出JS引擎的参数长度限制的风险。如果参数数组可能非常大,推荐使用下面这种策略来处理:将参数数组切块后循环传入目标方法:

    function minOfArray(arr){

        const min = Infinity;

        const QUANTUM = 32768;

        for(let i = 0, len = arr.length; i < len; i += QUANTUM){

            const submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));

            min = Math.min(submin, min);

        }

        return min;

    }

    const min = minOfArray([5,6,2,3,7]);

3. function.bind(thisArg[, arg1[, arg2[,...]]])

    参数:

    thisArg: 调用绑定函数时作为this参数传递给目标函数的值。如果使用new运算符构造绑定函数,则忽略该值。

    arg1,arg2,...: 当目标函数被调用时,预先添加到绑定函数的参数列表中的参数。

    说明:

    bind()函数会创建一个新的绑定函数,调用绑定函数通常会导致执行包装函数。

    示例:

    创建绑定函数:

    bind()最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的this值。常见一个错误是将一个方法从对象中拿出来,然后调用,期望方法中的this是原来的对象。如果不做特殊处理,一般会丢失原来的对象。

this.x = 9;    // 在浏览器中,this指向全局的"window"对象

const module = {

    x: 81,

    getX: function(){ return this.x; }

};

module.getX();    // 81

const retrieveX = module.getX;

retrieveX();    // 返回9 因为函数是在全局作用域中调用的

const boundGetX = retrieveX.bind(module);    // 创建一个新函数,吧this绑定到module对象

boundGetX();    // 81

偏函数:

    bind()的另一个最简单的用法是使用一个函数拥有预设的初始化参数。将这些参数作为bind()的参数写在this后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。

function list(){

    return Array.prototype.slice.call(arguments);

}

function addArguments(arg1, arg2){

    return arg1 + arg2;

}

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

const result1 = addArguments(1,2);    // 3

const leadingThirtysevenList = list.bind(null, 37);    // 创建一个函数,它拥有预设参数列表

const addThirtySeven = addArguments.bind(null, 37);    // 创建一个函数,他拥有预设的第一个参数

const list2 = leadingThirtysevenList();    // [37]

const list3 = leadingThirtysevenList();    // [37, 1, 2, 3]

const result2 = addThirtySeven(5);    // 37 + 5 = 42

const result3 = addThirtySeven(5, 10);    // 37 + 5 = 42,第二个参数被忽略

以上就是这三个方法的讲解,注意的是:call()方法的作用和apply()方法类似,只有一个区别就是call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组。

相关文章

网友评论

      本文标题:讲解call() apply() bind()方法

      本文链接:https://www.haomeiwen.com/subject/myjgpqtx.html