JS如何封装一个库2

59 阅读1分钟

实现链式调用

$('.red').addClass('green').addClass('big')

只需在addClass里加上一句话 return this

addClass(className) { 
    this.标签数组.forEach((标签) => {
        标签.classList.add(className)
    })
    return this  //this到底是什么
}

三种途径确定this值

  1. 查看MDN文档
  2. 查看浏览器源码(C++)或库源码(JS)
  3. 看函数调用(不能看函数声明)

函数的5种调用形式

  1. fn(参数1) this = window | undefined
  2. obj.x.method(参数1) this = obj.x
  3. fn.call(神秘参数, 参数1) this = 神秘参数
  4. fn.apply(神秘参数, [参数1]) this = 神秘参数
  5. new fn(参数1) new中的this表示新构造的对象

代码示例

const obj = {
    name: 'obj',
    fn() {
        console.log('this:' + this.name)
    }
}
window.name = ''

obj.fn()//第1次打印 'this:obj'
const fn = obj.fn; fn()//第2次打印 'this:'
[obj.fn][0]()//第3次打印 'this:undefined' arr=[obj.fn] arr[0]()=>arr.0() this=>arr 
let f; (f = obj.fn)()//第4次打印 'this:'