call 和 apply 的使用

来源:互联网 发布:那个基金软件好 编辑:程序博客网 时间:2024/06/10 02:16

   call 和 apply 都是改变当前执行函数的上下文,也就是改变this的指向。

  call的语法 fun.call(thisArg[, arg1[, arg2[, ...]]])

apply的语法fun.apply(thisArg, [argsArray])

var pet = {words: '...',speak: function (name) {console.log('I am ', name, 'speak: ', this.words);console.log('print this = ', this)}}var dog = {words: "wang"}pet.speak('animal');console.log("-----call--------");pet.speak.call(dog, 'xiaohua');console.log("-----apply--------");pet.speak.apply(dog, ['xiaohua']);

打印结果