20200223

@czhang
  • date: 20200223
  • author: czhang

Plan

你不知道的 JavaScript 第二部分 第二章结束

Notes

1. this 绑定四条规则优先级问题

  1. 默认绑定优先级最低
  2. 显式绑定 > 隐式绑定
  3. new 绑定 > 隐式绑定 ==> function foo(){} new foo > obj.foo
  4. new 绑定 & 显示绑定
    1. 无法使用 new fool.call(obj) ,因为 call 返回的不是一个函数,因此 可以使用 bind 来进行对比
    2. new 会生成一个新的对象,绑定在新对象上,并不改变之前的绑定

2. 绑定例外

  1. 把 null/undefined 作为 this 的绑定对象传给 call apply bind, 会被自动忽略,应用默认绑定

    1. foo.call(null)
    2. 应用:展开数组:
      1. foo.apply(null,[2,3,4])
      2. foo.bind(null,1)(2)
    3. 由于使用 null 可能会默认绑定到 全局对象中,因此为了安全,可以创建一个 “DMZ” 对象
      1. 使用 Object.create(null) 不会创建 Object.prototype ,因此比 “{}” "更空"
  2. 间接引用

    1. 赋值表达式返回值是目标函数的引用
    function foo()
        console.log('a', this.a);
    }
    var a = 2;
    var o = { a: 3, foo: foo };
    var p = { a: 4 };
    p.foo = o.foo;
    p.foo(); // a 4
    (p.foo = o.foo)(); // a 2
    

3. 软绑定

  1. 对应绑定进行修改,可以通过隐士绑定或者显示绑定来修改 this
  2. 做法:判断 this 是否为 全局对象/undefined ,如果是 则绑定指定对象

More

mdn 查看 bind function polyfill 尝试理解