function foo() { // 当前调用栈 => foo // 当前调用位置 => global全局做用域 console.log('foo') bar() // bar调用位置 } function bar() { // 当前调用栈 => foo -> bar // 当前调用位置 foo console.log('bar') }
默认 => 独立函数调用app
隐式 => 是否存在上下文 / 被某个对象拥有或包含函数
function foo() { return this.a } const obj = { a: 'hello', foo, // 函数引用,当前上下文是obj } obj.foo()
显式绑定 => call, apply, bindthis
function foo() { return this.a } const obj = { a: 'hello } const bar = function() { foo.call(obj) // 显式的强制绑定 } setTimeout(bar, 300) bar.call(window) // 2 => 硬绑定以后this没法再修改
new绑定 => 构造函数调用,实际上并不存在“构造函数”,是对函数的“构造调用”code
隐式绑定会丢失绑定对象,从而应用默认绑定,分别有如下两种状况。对象
函数别名 => 引用函数自己,so默认绑定作用域
function foo() { return this.a } const obj = { a: 'hello', foo, // 函数引用,当前上下文是obj } const a = 'on no, this is global' const bar = obj.foo // 函数别名 bar() // 'on no, this is global'
参数传递 => 隐式赋值,同上io
function foo() { return this.a } function doFoo(fn) { fn() // fn => foo } const obj = { a: 'hello', foo, // 函数引用,当前上下文是obj } const a = 'on no, this is global' doFoo(obj.foo) // 'on no, this is global'
new能够修改显式的thisconsole
function foo(some) { this.a = some } const obj = {} const bar = foo.bind(obj) bar(2) console.log(obj.a) // 2 const baz = new bar(3) console.log(obj.a) // 2 console.log(baz.a) // 3 => new 修改了this绑定
new中使用硬绑定 => 函数柯理化function
function foo(a, b) { this.value = a + b } const bar = foo.bind(null, 'hello ') //这里 this不指定,new时会修改 const baz = new bar('world') baz.value // 'hello world'