zoukankan      html  css  js  c++  java
  • 改变this指向的方法

    call()

    它可以用来调用所有者对象作为参数的方法。通过call()能够使用属于另一个对象的方法。

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

    call() 方法可接受参数:

    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()和apply()之间的区别:

    call()方法分别接受参数。

    apply()方法接受数组形式的参数。

    如果要使用数组而不是参数列表,则 apply() 方法非常方便。

    带参数的apply()方法:

    接受数组中的参数。

    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"John",
      lastName: "Doe"
    }
    person.fullName.apply(person1, ["Oslo", "Norway"]);

    bind()  //不太明白

    bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上.

  • 相关阅读:
    算法经典文章收藏
    Python 学习文章收藏
    Leetcode 刷题计划
    CLR via C# 学习计划
    算法导论 学习计划
    算法导论学习笔记 一 分治算法
    Mongodb 学习笔记
    Python模拟HttpRequest的方法总结
    在Github上搭建自己的博客(Windows平台)
    Git Shell 基本命令(官网脱水版)
  • 原文地址:https://www.cnblogs.com/Willa-Wei/p/13742511.html
Copyright © 2011-2022 走看看