Javascript / Nodejs call 和 apply

call: 改变了函数运行的作用域,即改变函数里面this的指向
apply:同call,apply第二个参数是数组结构

例如:
this.name = 'Ab'
var obj = {name: 'BBC'}

function getName(){
return this.name;
}
console.log(getName.call(this))
console.log(getName.call(obj))

console:
Ab
BBC

继承功能:
function Person(name, age, sex){
this.name = name
this.sex = sex
this.age = age
this.getAge = function() {
return this.age
}
}

function Student(name, age, sex, grade){
Person.call(this, name,age,sex)
  //Person.apply(this, arguments)
this.grade = grade
}
var stu = new Student('xiaoming', 23, 'male','one grade')
console.log(stu.name)
console.log(stu.age)
console.log(stu.sex)
console.log(stu.grade)
console.log(stu.getAge())
console: 

  xiaoming
  23
  male
  one grade
  23



 

posted @ 2019-05-06 17:45  一样菜  阅读(554)  评论(0编辑  收藏  举报