javascript 中 call()、apply()、bind() 的用法

92 阅读1分钟

javascript 中 call()、apply()、bind() 的用法

call 方法使用一个指定的this值和单独给出一个或多个参数来调用一个函数

/**
 *  语法
 * thisArg: 可选,在function 函数运行时使用的this值
 * arg1,arg2 可选:指定的参数列表
 * function.call(thisArg,arg1,arg2)
 */
// 示例
let person1 = {
    firstName: 'zhang',
    lastName: 'fan',
    fullName: function(arg1,arg2){
        return this.firstName + " " + this.lastName + " " + arg1 + " " + arg2;
    }
}

let person2 = {
    firstName: 'tom',
    lastName: 'join'
}

let result = person1.fullName.call(person1,'a','b');
console.log(result)

apply apply() 方法调用一个具有给定this值的函数,以及以一个数组的形式提供的参数。 call()接受一个参数列表,而apply() 接受一个参数的单数组

// 语法
/**
 * //thisArg: 在func 函数运行时 使用this 值
 * argsArray: 可选,一个数组或者类数组对象,其中的数组元素将作为单独的参数传给func函数。
 * apply(thisArg,argsArray)
 */
{
    let person1 = {
        firstName: 'zhang',
        lastName: 'fan',
        fullName: function(args){
            return this.firstName + " " + this.lastName + " " + args[0] + " " + args[1]; 
        }
    }

    let person2 = {
        firstName: 'tom',
        lastName: 'join'
    }

    let result = person1.fullName.apply(person2,['a','b']);
    console.log(result)
}


bind

//bind
{
    let  person1 = {
        firstName: 'zhang',
        lastName: 'fan',
        fullName:function(arg1,arg2){
            return this.firstName + this.lastName + arg1 + arg2;
        },
        getFullName:function(args){
            return this.firstName + this.lastName + args[0] + args[1];
        }
    };
    let person2 = {
        firstName: 'tom',
        lastName: 'liming'
    }

    let result1 = person1.fullName.bind(person2,'a','b')()
    let result2 = person1.getFullName.bind(person2,['a','b'])()
    console.log(result1)
    console.log(result2)

}
{
   console.log(Math.max.apply(null,[1,2,3]))
   console.log(Math.max.apply(" ",[1,2,3]))
   console.log(Math.max.apply(0,[1,2,3]))
}

闭包

{
    (function(){
        var x='hello';
        console.log(x)
    })();
}

{
    const x = (x,y) => x*y;
    console.log( x(2,3));

    const y = (x,y) => {return x*y};
    console.log(y(3,4))
}

{
    function findMax(){
        var max = -Infinity;
        
        for(var i=0;i<arguments.length;i++){
            if(arguments[i]>0){
                max = arguments[i];
            }
            return max;
        }
    }
    console.log(findMax(99,11,33))
}

{
    function sumAll(){
        let i,sum = 0;
        for(i=0;i<arguments.length;i++){
            sum += arguments[i];
        }
        return sum;
    }
    console.log(sumAll(1,2,3,4))
  
}

{
    var add = (function(){
        var count = 0;
        return function (){
            return count +=1;
        }
    })();

    console.log(add());
    console.log(add());
}