zoukankan      html  css  js  c++  java
  • javascript的call和apply区别

    call/apply
    作用是改变this指向,区别后面传的参数形式不同

    看一下例子

    function Person(name, age) {
      // this = obj
      this.name = name
      this.age = age
    }
    var obj = {
    }
    Person.call(obj, 'lyj', 18)  //函数执行会默认调用call, 比如Person.call()
    console.log(obj)             //{age: 18, name: 'lyj'} call第一个参数,使this指向obj, 第二个参数起为函数传的参数

    再看以下例子

    function Person(name, age, sex) {
      this.name = name
      this.age = age
      this.sex = sex
    } 
    function Student(name, age, sex, tel, score) {
      Person.call(this, name, age, sex)  //使Person里面的this指向Student的this, 借用Person的功能制造出Student的功能
      // this.name = name
      // this.age = age
      // this.sex = sex
      this.tel = tel
      this.score = score
    }
    var student = new Student('lyj', 18, '男', 662130, 90)
    console.log(student)
    //改变this指向理解为,自身没有的功能借助别的构造函数来实现自身的功能
    
    //apply与call类似,传参形式不同
    var obj = {}
    Person.call(obj, 'lyj', 18, '男')  //call, 第二个参数起可以传多个参数,实参个数等于形参个数
    Person.apply(obj, ['lyj', 18, '男'])  //apply, 第二个参数为实参列表arguments, 而且只能一个参数 

    end !!!

  • 相关阅读:
    css样式的六种选择器
    css 颜色表示法
    css 文本设置
    “http”和“https”的区别是什么?优缺点是什么?
    Httpclient
    接口认证:Bearer Token(Token 令牌)
    哪个参数用来区分请求来自客户(手机)端还是服务器(PC)端?
    常用的HTTP响应头
    Http 请求头包含哪些信息?
    单例集合的体系
  • 原文地址:https://www.cnblogs.com/lyjfight/p/13815514.html
Copyright © 2011-2022 走看看