绑定规则及优先级
- new 绑定:new foo()
- 显示绑定:call,apply,bind
- 隐式绑定:对象调用(obj.foo()),谁调用指向谁
- 默认绑定:默认指向window
箭头函数
箭头函数本身没有this,this指向由外层函数的作用域决定,父级this指向谁,箭头函数的this就指向谁。上面四项绑定规则对箭头函数都无效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| var a = 0 function foo (b) { console.log(this) var test = () => { console.log(this) } return test } var obj1 = { a: 1, foo: foo, } var obj2 = { a: 2 foo: () => { console.log(this) } } obj1.foo()() var bar = foo.call(obj1) obj2.foo()
var foo1 = () => { console.log(this) } new foo1()
|
练习题1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| var name = 'window' var obj1 = { name: '1', fn1: function(){ console.log(this.name) }, fn2: () => {console.log(this.name)}, fn3: function(){ return function(){ console.log(this.name) } }, fn4: function(){ return () => { console.log(this.name) } }, } var obj2 = { name: '2' }
obj1.fn1() obj1.fn1.call(obj2)
obj1.fn2() obj1.fn2.call(obj2)
obj1.fn3()() obj1.fn3().call(obj2) obj1.fn3.call(obj2)()
obj1.fn4()() obj1.fn4().call(obj2) obj1.fn4.call(obj2)()
|
练习题2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function Foo() { getName = function() { console.log(1) } return this } Foo.getName = function(){ console.log(2) } Foo.prototype.getName = function(){ console.log(3) } var getName = function(){ console.log(4) } function getName (){ console.log(5) }
Foo.getName() getName() Foo().getName() getName()
new Foo.getName() new Foo().getName() new new Foo().getName()
|