zoukankan      html  css  js  c++  java
  • js call()、apply()、bind()的区别和使用

    js call()、apply()、bind()的区别和使用

    写在前面:

    • call和apply可以用来重新定义函数的执行环境,也就是this的指向; call 和 apply 都是为了改变某个函数运行时的
      context 即上下文而存在的 换句话说,就是为了改变函数体内部 this 的指向。因为 JavaScript
      的函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。

    • call() 就是用来让括号里的对象 来集成括号外的函数的属性!可以称之为继承!

    call:

    目的: 改变函数运行时的上下文(context),即this指向
    说人话: 就是“劫持”(继承)别人的方法
    例子:person.fullName.call(person1) 即 对象person1继承了person的fullName方法

    var person = {
        fullName: function() {
            return this.firstName + " " + this.lastName;
        }
    }
    var person1 = {
        firstName:"Bill",
        lastName: "Gates",
    }
    person.fullName.call(person1);  // 将返回 "Bill Gates"
    

    另外: call()也可以传递其他参数:call(thisObj, arg1, arg2, arg3, arg4);

    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"Bill",
      lastName: "Gates"
    }
    person.fullName.call(person1, "Seattle", "USA");
    

    打印结果:

    apply: 同 call

    目的: 改变函数运行时的上下文(context),即this指向
    例子:person.fullName.apply(person1) 即 对象person1继承了person的fullName方法
    和call的区别: 传递其他参数时需要使用[]
    传递其他参数:apply(thisObj, [arg1, arg2, arg3, arg4]);

    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"Bill",
      lastName: "Gates"
    }
    person.fullName.apply(person1, ["Seattle", "USA"]);
    

    打印结果:

    bind: 同call、apply

    目的: 改变函数运行时的上下文(context),即this指向
    和call、apply的区别: 使用的返回值是个方法,也就是bind(thisObj)()实现
    传递其他参数:bind(thisObj, arg1, arg2, arg3, arg4)();

    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"Bill",
      lastName: "Gates"
    }
    person.fullName.bind(person1, "Seattle", "USA")();
    

    打印结果:

  • 相关阅读:
    xt
    UVA 10200 Prime Time (打表)
    CodeForces 540B School Marks
    CodeForces 540C Ice Cave (BFS)
    poj 3250 Bad Hair Day(栈的运用)
    hdu A Magic Lamp
    hdu 4325 Flowers(区间离散化)
    hdu 5500 Reorder the Books
    V2X之标准
    V2X的前生今世
  • 原文地址:https://www.cnblogs.com/nangezi/p/14109044.html
Copyright © 2011-2022 走看看