首先js中的函数调用有三种形式
func(p1, p2)
obj.child.method(p1, p2)
func.call(context, p1, p2)
前面两种都是语法糖,可以等价地变为 call 形式。
func(p1, p2) 等价于
func.call(undefined, p1, p2)
obj.child.method(p1, p2) 等价于
obj.child.method.call(obj.child, p1, p2)
而this指向的便是函数中的context即上下文,或函数当前运行环境。
当我们在浏览器控制台中写下下面的函数:
function func(){
console.log(this)
}
func()
其等价于
func.call(undefined)
在浏览器中undefined默认的context为window对象。
如果将代码改为:
function func(){
console.log(this)
}
func.call({id:1})
则结果变为
这是因为函数当前运行的环境由undefined变为了{id:1}
这个对象。
举几个例子:
function Cat(){
name: 'kitty',
print: function(s=''){console.log(s+this.name)}, // context是类为Cat的对象
init: function() {
button.addEventListener('click',
function(){this.print('init ')};
} // context是button
}
setInterval(function(){console.log(this),1000) // context为全局对象window
箭头函数是es6加入的函数定义方式相当于其他语言中的匿名函数
var f = () => {console.log('hello!')}
等价于
function f(){console.log('hello!')}
箭头函数具有如下特点,也可以说是于普通函数定义的不同之处:
- 箭头函数没有自己的this。箭头函数的this是相同情况下function的上一级作用域的运行环境。
- 不同时也没有自己的arguments、super、new.target,这点和this一样。
- 因为没有this,所以不能当构造函数。
- 不可以使用yield命令,因此箭头函数不能用作 Generator 函数。
同样举几个例子:
function Timer() {
this.s1 = 0;
this.s2 = 0;
// context为Timer
setInterval(() => this.s1++, 1000);
// context为window
setInterval(function () {
this.s2++;
}, 1000);
}
普通函数的context为全局对象window,因为setInterval
是全局对象window内的一个函数,而箭头函数没有自己的this,它的context需要通过在setInterval
的上一级作用域中寻找,也就是Timer。
var handler = {
id: '123456',
init: function() {
document.addEventListener('click',
event => this.doSomething(event.type), false); //context为handler
},
doSomething: function(type) {
console.log('Handling ' + type + ' for ' + this.id);
}
};
同样的上述箭头函数换成普通函数则context为document。
function foo() {
return () => {
return () => {
return () => {
console.log('id:', this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1
由于函数foo
内返回的都是箭头函数,因此只有一个this,就是函数foo的this,在这里被call()
定义为对象{id:1}
。
// ES6
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
// ES5
function foo() {
var _this = this;
setTimeout(function () {
console.log('id:', _this.id);
}, 100);
}
箭头函数的作用相当于在函数开头是声明var _this = this
,将_this
在函数foo
中的值固定下来,以免后续this不断的变化。