Home  >  Q&A  >  body text

javascript - Questions about apply() and call()

function sum(num1,num2) {
    return num1 + num2;
}
function callSum1(num1,num2) {
    return sum.apply(this,arguments);
}
function callSum2(num1,num2) {
    return sum.apply(this,[num1,num2]);
}

alert(callSum1(10,10));
alert(callSum2(10,10));

//call()例子就省略了

Question:
1.sum.apply(this,arguments) refers to the object sum calling the apply method. This refers to callSum() and sum() both running in the same scope. arguments refers to "sum1, sum2"?
2. What is the application value of apply() and call() in the project?

滿天的星座滿天的星座2663 days ago1136

reply all(5)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-07-05 11:03:57

    What’s written above is really complicated:)

    Listen to me, what the questioner is confused about
    1:

    function callSum1(num1,num2) {
        return sum.apply(this,arguments);    // 这里的arguments和下面的[num1,num2]是同一个意思
    }
    function callSum2(num1,num2) {
        return sum.apply(this,[num1,num2]);
    }

    arguments is an array-like object corresponding to the arguments passed to the function. The arguments object is a local variable available in all functions. You can use the arguments object to reference a function's arguments within a function.

    PS: The point of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this points to. In fact, the final point of this is the object that calls it

    2. Application value of call and apply (meaning of existence):

    The functions exist to change the function runtime context. That is to change the pointing of this inside the function body
    "To put it bluntly, a has xx method, but b does not. B can ask a to borrow it!" (Isn't this just inheritance~)

    The difference between call and apply:

    The ways of accepting parameters are different.

    As follows:
    call accepts continuous parameters, and apply accepts array parameters.
    A.call(this, a,b,c,d)
    A.apply(this, [a,b,c,d])

    A portal: http://www.jianshu.com/p/a7b1...

    reply
    0
  • typecho

    typecho2017-07-05 11:03:57

    1. arguments is one of the built-in attributes of function, which represents the function array object, that is, the arguments in callSum1 refer to num1 and num2
      https://developer.mozilla.org...

    2. The value of
    3. apply and call is that it can make this in the specified function point to a specific object. For example, the dom we obtain using document.querySelectorAll() is actually an array-like object, not an array. If you want When you want to use the array method, you can do this

    var doms = document.querySelectorAll('p');
    [].forEach.call(doms, function(e){
        //遍历元素
    });

    The main difference between apply and call is the parameter format. It is recommended that the subject refer to MDN.

    reply
    0
  • 巴扎黑

    巴扎黑2017-07-05 11:03:57

    1.sum.apply(this,arguments) refers to the object sum calling the apply method. This refers to callSum() and sum() both running in the same scope. Arguments refers to "sum1, sum2"?

    2. What is the application value of apply() and call() in the project?

    For 1 execution results both return 20 20

    sum.apply(this,arguments) refers to using apply to call sum. Specify that this when sum is executed is the current this. The following arguments are the parameter list, which is an array-like object. You can simply treat it as an array. .

    sum.apply(this,[num1, num2]) Similar to above.

    Regarding arguments, post a screenshot and you may have a perceptual understanding


    The following is the answer to the second point

    Hand-picked this

    It’s easier to understand, just change this pointer, for example, during the success callback of an ajax request

    For example, when developing vue, if there is no arrow function, you have to use var that = this to temporarily store this. If you can handpick this, you won’t have these problems

    Give me a chestnut

    function sayName(){
        console.log(this.name); 
    }
    
    var xiao_ming = {
        name: '小明妹妹'
    }
    
    // 钦点 this 
    sayName.call(xiao_ming); 

    Convert array-like objects into true arrays

    arguments stores the parameter list of the function in the form of an array-like object.

    function sumAll(){
        var argu = Array.prototype.slice.call(arguments); 
        
        // 从 0 开始积、每次 sum + cur 作为下次的 sum 
        return argu.reduce((sum, cur) => sum + cur, 0); 
    }

    In fact, we can see from here: executing slice only requires the object to have length correct subscript, and then it can be executed normally and the result returned.

    Because many methods of arrays can be used on array-like objects, array-like objects can indeed be considered arrays in many cases.

    // 声明一个类数组对象 
    var a = {
        0: 'hello',
        1: 'seg',
        2: 'ment',
        3: 'fault',
        length: 4
    }
    
    // forEach 
    Array.prototype.forEach.call(a, elem => console.log(elem)); 
    // => 遍历打印
    
    // reduce 
    var helloSF = Array.prototype.reduce.call(a, (acc, cur) => acc + cur + ' ', ''); 
    console.log(helloSF); 
    // => 
    // "hello seg ment fault "
    


    You can also make it more like an array

    var a = {
        0: 'hello',
        1: 'seg',
        2: 'ment',
        3: 'fault',
        length: 4
    }
    
    a.__proto__ = Array.prototype; 
    a.forEach(e => console.log(e)); 
    Array.prototype.reduce.call(a, (acc, cur) => acc + cur + ' ', ''); 

    Object Really Like Array

    Implement partial function Partial Function

    Similar to partial functions in mathematics, such as:

    Functionf(x, y) = x + y
    If we let y = k then we can get the partial function f(x, k) = x + k
    ( Or this may be better understood: f (x, 4) = x + 4 )

    Bind is generally used to implement partial functions. However, apply, call and bind should be discussed intensively.

    function logger(type){
        return console.log.bind(console, type); 
    }

    Use apply to implement the above logger is:

    function logger2(type){
        return function(){
            var argu = Array.prototype.slice.call(arguments);  
            argu.unshift(type); 
            console.log.apply(console, argu); 
        }
    }

    Higher-order functions and currying

    Higher-order functions generally refer to functions whose return value is a function or whose parameters are functions.

    setTimeout is a good example. It accepts a parameter (usually a function) and executes it after a certain delay.
    But after passing it in, this usually points to the global object window. If you want to specify this, you have to use call apply and bind

    The logger2 above does this and returns a function


    About currying, let’s look at the function first add

    function add(x, y){
        return a + b; 
    }
    
    add(1, 2); 
    // => 
    // 3 

    If the parameters can be passed one by one, the result will be obtained when passed to the second one:

    var add1 = add(1); 
    add1(2); 
    // => 3 
    
    add(3)(4); 
    // => 7

    The first execution returns a function. If add is regarded as a mathematical function, it is f(x, y) = x + y We executed add(1) once and got add1 In fact Just let x = 1, so we get the partial function

    f(1, y) = 1 + y

    Execute y for the second time and you will get the actual value, and the result can be calculated using the formula.

    This is actually a step-by-step process of elimination.


    What is it for?

    I am new to functional programming and have not yet grasped the essence. The only use of currying is lazy evaluation
    The operation just now will not run until all the parameters are given, and it will be calculated when the parameters are enough. result.


    I stayed up most of the night and browsed SF. All I could think of was this. . . .

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 11:03:57

    Manually set thisscope.

    reply
    0
  • 迷茫

    迷茫2017-07-05 11:03:57

    You will know after searching on Baidu.

    reply
    0
  • Cancelreply