获取全局对象
- web:window、self、frames、globalThis、this
- node:global
- worker:self
- 通用:globalThis
1 | var a = '全局属性 a' |
this:Javascript 关键字,当前环境执行上下文对象的属性,存在作用域问题
- 全局作用域 this === window
- 作用域内部 this 指向调用者
类 this
Class:理解为容器、作用域、壳子,严格模式
new Class 指向 Class 内部的 constructor 构造器函数
1 | class Test{ |
- 类的非静态方法
1 | class Test{ |
类继承
1 | class Father{ |
Must call super constructor in derived class before accessing 'this' or returning from derived constructor
子类 constructor 中必须调用 super(),在使用 this 之前
- super()
调用 Father 的 constructor
生成 this 绑定,Father 中 this 指向 Son 实例
Son 中 this 指向 new Father() -> {age}
构造函数
1 | function Test(){ |
call、apply、bind
fn.call(obj, a, b, c)
fn.apply(obj, [a, b, c])
bind:使用方法和 call 一样,效果只会生效一次
1 | let obj = {a: 1} |
箭头函数
箭头函数忽略任何形式的 this 指向改变,静态 this 指向
箭头函数一定不是一个构造器
箭头函数的 this 不是谁调用指向谁,而是指向外层非箭头函数作用域的 this
对象
对象内部的 this,就近引用,谁调用指向谁
1 | var obj = { |
Object.create({...指定原型 || null:创建无链对象})
1 | Object.defineProperty(obj, 'a', { |
事件处理函数
谁绑定处理函数,this 指向谁
1 | ;(function(doc){ |