美文网首页小码农养成记
JavaScript 中的 call、apply、bind 和

JavaScript 中的 call、apply、bind 和

作者: F_wind | 来源:发表于2021-10-26 22:18 被阅读0次

    JavaScript

    call :改变 this 指向,第一个参数是新指向的 this,后面是 arguments 参数,接收形式是逗号间隔的参数;
    apply:用法与 call 类似,arguments 参数接收形式改为数组;
    bind:用法与 call 类似,调用以后返回一个函数引用,如果需要实现 call 效果,则需要在后面加小括号 () ,就可以直接执行了。

    例子:

    var name = "Tom",
      age = 12;
    var userInfo = {
      name: "Jack",
      newAge: this.age,
      get: function (arg1) {
        var that = this;
        return (
          "name:" +
          this.name +
          ",age:" +
          this.age +
          ",from:" +
          arg1 +
          ",to:" +
          arguments[1]
        );
      },
    };
    console.log(userInfo.name); // Jack
    console.log(userInfo.newAge); // undefined
    console.log(userInfo.get()); // name:Jack,age:undefined,from:undefined,to:undefined
    
    var user1 = { name: "Lucy", age: 5 };
    console.log(userInfo.get.call(user1)); // name:Lucy,age:5,from:undefined,to:undefined
    console.log(userInfo.get.apply(user1)); // name:Lucy,age:5,from:undefined,to:undefined
    console.log(userInfo.get.bind(user1)()); // name:Lucy,age:5,from:undefined,to:undefined
    console.log("#########");
    console.log(userInfo.get.call(user1, "US", "china")); // name:Lucy,age:5,from:US,to:china
    console.log(userInfo.get.apply(user1, ["US", "china"])); // name:Lucy,age:5,from:US,to:china
    console.log(userInfo.get.bind(user1, "US", "china")()); // name:Lucy,age:5,from:US,to:china
    

    相关文章

      网友评论

        本文标题:JavaScript 中的 call、apply、bind 和

        本文链接:https://www.haomeiwen.com/subject/oktualtx.html