zoukankan      html  css  js  c++  java
  • [Javascript] Specify this using .call() or .apply()

    A function's this argument is usually set implicitly, depending on how the function is called. Ordinary function calls, method calls, and constructor calls all lead to a different this value.

    We can also call a function with an explicit this argument using Function.prototype.call() or Function.prototype.apply(). Both methods accept a thisArg as their first parameter and a variable number of additional arguments.

    This lesson shows how to use call() and apply() and explains how they differ.

    const numbers = [1, 2, 3, 4, 5];
    
    // All the same
    const slice1 = numbers.slice(1, 4);
    const slice2 = numbers.slice.call(numbers, 1, 4);
    const slice3 = numbers.slice.apply(numbers, [1, 4]);

    Notice if you are not using "strict" mode, call() and apply() has some problem:

    // If not using strict mode,  null and undefined value passed in .call() and .apply() will be ignored! this will be set to global. And this will not happen in strict mode
    
    function foo() {
      console.log(this == global)
    }
    
    foo.call(null)  // true
    foo.call(undefined) // true
    
    foo.apply(null) // true
    foo.apply(undefined) // true
  • 相关阅读:
    H3C IS-IS基础配置
    H3C OSPF实验大集合(IPv4)
    H3C OSPF实验大集合(IPv6)
    H3C RIP实验大集合
    H3C IPv4和IPv6负载均衡
    H3C IPv4与ipv6静态路由
    H3C 配置dns及arp
    H3C 配置DHCP服务器
    H3C 多生成树MSTP
    H3C 配置ftp服务器
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8023478.html
Copyright © 2011-2022 走看看