zoukankan      html  css  js  c++  java
  • call、apply、bind用法

    1.call

    // 作家
    var Writer = {
    income:0, // 收入
    record:[], // 收录/明细
    compute(){
    var arg = arguments;
    for(var i = 0; i < arg.length; i++){
    var item = arg[i];
    for (const key in item) {
    if (item.hasOwnProperty(key)) {
    this.income += item[key];
    }
    }
    this.record.push(item); //添加每一笔收入的明细
    }
    }
    }
    Writer.compute({'盗墓笔记':100},{'从你的全世界路过':200},{'那些年追过的女孩':300});
    // 画家
    var Painter = {
    income:0,
    record:[], // 收录/明细
    }
    Writer.compute.call(Painter,{'大自然写生':300},{'海':20},{'树':77})
    2.apply
    // 题目
    var testArr = [];

    for(var i = 0; i < 5; i++){
    testArr.push(i);
    }
    var a = [3333];
    a.push(...testArr);
    a.push.apply(a,testArr)

    3.bind和call的区别

    bind:1.改变函数作用域  2.返回一个新函数

    eg:

    var obj = {name:'obj'}

    var bindHandle = handle.bind(obj)

    function handle(){
    console.log(arguments.callee)
    console.log(this.name);
    document.body.removeEventListener('click',arguments.callee);
    }


    document.body.addEventListener('click',handle.bind(obj))

    call:执行函数

    handle.bind(obj);


  • 相关阅读:
    TCP之Nagle算法与TCP_NODELAY
    CSPS模拟 87
    CSPS模拟 86
    CSPS模拟 85
    CSPS模拟 84
    CSPS模拟 83
    CSPS模拟 82
    CSPS模拟 81
    CSPS模拟 80
    CSPS模拟 79
  • 原文地址:https://www.cnblogs.com/miaSlady/p/9304440.html
Copyright © 2011-2022 走看看