zoukankan      html  css  js  c++  java
  • 关于js中的call

    javascript中的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(person2);  //打印结果是"Steve Jobs"

    以上案例总结 作用一:call()可以调用某一函数

    var person = {
      fullName: function(city, country) {
        console.log(this)
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"Bill",
      lastName: "Gates"
    }
    var person2 = {
      firstName:"Steve",
      lastName: "Jobs"
    }
    person.fullName.call()  //这样调用this指向window
    person.fullName.call(person1) //这样调用this指向person1这个对象

    以上案例总结 作用二:call()可以这个函数的this指向。

    另外,call()也可以接受参数,比如:

    var person = {
      fullName: function(city, country) {
        console.log(this)
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"Bill",
      lastName: "Gates"
    }
    var person2 = {
      firstName:"Steve",
      lastName: "Jobs"
    }
    person.fullName.call(person1,'CHINA','BeiJing') //打印结果为"Bill Gates,CHINA,BeiJing"
  • 相关阅读:
    学习方法与经验总结
    工具综合症?资料收集狂?
    SpringMVC 过滤器Filter使用解析
    Spring 管理Filter和Servlet
    pom.xml配置详解
    开发Java web应用程序的介绍
    java web构建学习(概念基础)
    题目1474:矩阵幂
    题目1473:二进制数
    Python strip()方法
  • 原文地址:https://www.cnblogs.com/web001/p/14803610.html
Copyright © 2011-2022 走看看