javaScript 函数进阶

1.回调函数

        

<script>
      function f(n) {
        console.log('n=' + n)
      }
      function fn(a, cb) {
        let num = 10
        num += a
        // 调用函数cb
        cb(num)
      }
      fn(20, f)
</script>

2.函数的返回值

<script>
      let object = { id: 1 }
      function fn() {
        console.log(this) //?
        let num = 20
        let f = function () {
          console.log(this) // window
          console.log(num) // 20
        }
        f()
        return f
      }
      // let rt = fn()
      // rt()

      // call调用函数
      let rt1 = fn.call(object) // object调用fn函数
      rt1()
</script>

3.函数的作用域

call apply bind三者的区别:

    1、相同点

      调用函数,修改函数的this指向的方法,call apply bind三者都是Function原型对象的方法

    2、不同点

      2-1 call和apply可以直接调用函数,bind是返回一个函数,并没有执行函数

      2-2 call的参数使用,割开,apply传递的参数使用数组

      2-3 bind参数和call类型

<script>
  // var a // 预解析 变量提示 作用域提升
  // console.log(a) // undefined
  {
    //console.log(a) // 暂时性死区(tdz)
    var a = 10
    let b = 20 // let const 没有变量提升过程
  }
  //console.log(a) // 10
  // console.log(b) // 报错 b is not defined
  // let fn = new Function('a,b', 'return a+b')
  // console.log(fn(1, 2))
  let object = { id: 100, n: 20, m: 30 }
  function fn(a, b) {
    console.log('this.id=', this.id) // 100
    this.n = a
    this.m = b
    return a + b
  }
  let rt = fn.call(object, object.n, object.m)
  // console.log(rt) //50
  rt = fn.apply(object, [10, 20])
  // console.log(rt, object)
  // bind只是返回一个函数,不会直接调用函数
  rt = fn.bind(object, 1, 2)
  console.log(rt(), object)
</script>

4.函数的链式操作

<script>
      // 给元素添加内容
      function html(str) {
        this.innerHTML = str
        return this
      }

      // 给元素设置样式
      function css(key, value) {
        this.style[key] = value
        return this
      }

      let box = document.getElementsByClassName('box')[0] // HTMLDivElement
      box.html = function (str) {
        this.innerHTML = str
        return this
      }
      box.css = function (key, value) {
        this.style[key] = value
        return this
      }
      // let rt = html.call(box, 'hello world')
      // rt = css.call(rt, 'color', 'red')
      // rt = css.call(rt, 'font-size', '20px')
      box.html('hello').css('color', 'red').css('border', '1px solid black').html('world').css('color', 'blue')
    </script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值