js中call和apply

call/apply

作用用来改变this指向两者的区别是参数的传递不同,call传递的是变量, apply传递的是数组

    var obj = {
         name:'ghost',
         age:'20'
    }
    function Person(name,age){
      this.name = name
      this.age = age
      this.say = function(){
          console.log(this.name)
      }
    }
    var person =new Person("charry", 20) //charry 
    person.say() //这里的this,谁调用指向谁 所以指向person 
   person.say.call(obj) //ghost 这里改变过this指向,其this指向obj

function Person(name, age, sex){
    this.name = name
    this.age = age
    this.sex = sex
}
function Student(name, age ,sex, tel, grade){
    Person.call(this, name, age, sex) //调用Peson的方法来实习自己的函数,这里的this指向的是Student本身
    this.tel = tel;
    this.grade = grade
}
  var student = new Student('ghost', 18, 'male', 18208891933, 100)
  console.log(student.name, student.age) //ghost 18 
//  allpy 和 call 相同,只是传递参数的列表不同
 function Chip(mate,type){
       this.mate = mate
 }
 function Battery(capacity, company){
     this.capacity = capacity
     this.company = company
 }
 function Phone(mate, type, capacity, company){
     Chip.call(this, mate, type) //传递的是变量
     Battery.apply(this, [capacity, capacity]) //传递的是数组
 }
 var phone = new Phone('glod', 'Snapdragon855',"4000ma",'oppo')
console.log(phone.mate)
console.log(phone.company) 
上一篇:Mate 40系列发布 搭载华为运动健康服务带来健康数字生活


下一篇:华为折叠机皇突然上架淘宝:价格惊人