MDN中的this定义
当前执行代码的环境对象。程序员
多么简约凝练的归纳,寥寥11个字,将伴随程序员的前世此生。话很少说,让咱们一块儿探讨你不知道的thisapp
function foo() { console.log( this.a ); } var a = 10; foo();
答案:
10
this —> window
function foo() { console.log( this.a ); } var obj2 = { a: 42, foo: foo }; var obj1 = { a: 2, obj2: obj2 }; obj1.obj2.foo();
42
this -> obj2
function foo() { setTimeout(() => this.a = 1, 0) console.log( this.a ); } function foo2() { setTimeout(() => this.a = 1, 500) console.log( this.a ); } function doFoo(fn) { this.a = 4 fn(); } var obj = { a: 2, foo: foo, foo2: foo2 }; var a =3 doFoo( obj.foo ); setTimeout( obj.foo, 0 ) setTimeout( obj.foo2, 100 )
答案:
4
1
1
foo函数,第2行是一个定时器,哪怕定时器的延迟时间为0,仍然先执行第3行。故为4
当使用定时器调用函数时,先执行函数内代码,在进行函数调用。故为1
同理: 故为1
a = 3 function foo() { console.log( this.a ); } var obj = { a: 2 }; foo.call( obj ); foo.call( null ); foo.call( undefined ); foo.call( ); var obj2 = { a: 5, foo } obj2.foo.call() // 3,不是5! //bind返回一个新的函数 function foo(something) { console.log( this.a, something ); return this.a + something; } var obj = { a: 2 } var bar = foo.bind( obj ); var b = bar( 3 ); console.log( b );
答案:
2 undefined
3 undefined
3 undefined
3 undefined
3 undefined
2 3
5
第8行: this -> obj = 2, msg没有传值,故为undefined
第9~12行: 当call的第一个参数为null, undefined或者不传值时,只想window, this -> window = 3, msg没有传值,故为undefined
第25行:bind改变指向 -> obj,第26行:msg为3, 故为2 3
第27行:执行函数,为2+3 = 5
一个最多见的 this绑定问题就是被隐式绑定的函数会丢失绑定对象,也就是说它会应用默认绑定,从而把 this 绑定到全局对象或者 undefined 上,取决因而否是严格模式函数
function foo() { console.log( this.a ); } function doFoo(fn) { fn() } var obj = { a: 2, foo: foo }; var a = "oops, global"; doFoo( obj.foo );
答案: oops, global
第5行fn()引用第位置其实foo, 所以doFoo()至关因而一个不带修饰符的函数调用,所以应用了默认绑定—> window = oops, global
function foo(something) { this.a = something; } var obj1 = { foo: foo }; var obj2 = {}; obj1.foo( 2 ); console.log( obj1.a ); obj1.foo.call( obj2, 3 ); console.log( obj2.a ); var bar = new obj1.foo( 4 ); console.log( obj1.a );
答案:
2
3
2
4
new 绑定比隐式绑定优先级高,也闭隐式绑定绑定优先级高