JaveScript 笔记 call apply

参考博客- aveScript中this指向以及call(),apply()、bind() 的用法

1、总结:

  •         call,apply,bind函数目的都是为了将对象传递到函数里,只是带参方式不同
  •         js 函数内部如果使用了this,就不能直接调用函数,因为这样找不到this

2、call示例

   let obj = {
      name: 'xiaohua',
    }
    function fun_2(param) {
      console.log(obj == this) //true
      this.value = param
      console.log("fun_2>", this ," name:" + this.name) //fun_2> {name: "xiaohua", value: 123}  name:xiaohua
    }
    fun_2.call(obj, 123)
    console.log(obj) //{name: "xiaohua", value: 123}

3、错误示例   

如果直接执行函数会报错不能设置属性value,因为this不存在

    function fun_3(param) {
      console.log(obj == this,this) //false undefined
      this.value = param
      console.log("fun_2>", this ," name:" + this.name)
    }
    fun_3(5)
    //报错   TypeError: Cannot set property 'value' of undefined

4、对比测试 

    let id = 0
    function fun_4(...param) {
      id+=1
      this.id = id
      console.log("--------name: "+this.name+"-------------")
      console.log('this>',this)
      console.log('param>',param)
    }
    console.log('------------')
    let v4 = new fun_4(2, 3, 4)
    console.log('v4',v4)
    fun_4.apply({name:"applay"}, [1, 2, 3, 4])//数组方式传入可变参数列表
    fun_4.call({name:"call"}, 1, 2, 3, 4) //正常可变参数传入
    fun_4.bind({name:"bind"}, 1, 2, 3, 4)() //也是正常可变参数方式传入

 4.1、输出结果

--------name: undefined-------------
index.js:131 this> fun_4 {id: 1}
index.js:132 param> (3) [2, 3, 4]
index.js:136 v4 fun_4 {id: 1}
index.js:130 --------name: applay-------------
index.js:131 this> {name: "applay", id: 2}
index.js:132 param> (4) [1, 2, 3, 4]
index.js:130 --------name: call-------------
index.js:131 this> {name: "call", id: 3}
index.js:132 param> (4) [1, 2, 3, 4]
index.js:130 --------name: bind-------------
index.js:131 this> {name: "bind", id: 4}
index.js:132 param> (4) [1, 2, 3, 4]

5、apply特殊使用说明

apply可以用数组的方式传入可变参数,

一些函数定义时就是可变参数方式传入数据,但我们是数组时,总不能一个一个打出来吧。所以apply函数就有大作用了。

数组转字符串的函数原型如下:

String.fromCharCode(...codes: number[]): string

一般使用格式, 

      var str = String.fromCharCode(0x31,0x32,0x33,0x34)
      console.log(str) // 1234

 如果是一个数组,真的要一个一个打进去?难受!!!

    var array = [0x31, 0x32, 0x33, 0x34]
    var str2 = String.fromCharCode.apply(null,array)
    console.log(str2) // 1234

像这样就能搞定了。apply的this对象不需要传进去,用不到

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值