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()的第一个参数上.

  • 相关阅读:
    Docker 入门
    python3模块: sys
    Python sys os getpass 包的导入
    Python3模块: hashlib
    python3异常处理 try
    python3模块: uuid
    python3 内置函数详解
    servlet/和/*匹配的区别
    [转]任何程序员应该记住的性能指标
    [转]使用CMS垃圾收集器产生的问题和解决方案
  • 原文地址:https://www.cnblogs.com/Willa-Wei/p/13742511.html
Copyright © 2011-2022 走看看