普通函数中,内层函数不能从外层函数中继承this的值,在内层函数中,this会是window或者undefined,临时变量self用来将外部的this值导入到内部函数中(另外的方式是在内部函数执行.bind(this))
ES6中的箭头函数会直接调用的this是继承父级的this。
function fun(){ var self = this; setTimeout(function(){ console.log(this);//window console.log(self);//{id:1} console.log('id: ', self.id);//id: 1 },500); } fun.call({id:001});
function fun(){ var self = this; setTimeout(function(){ console.log(this);//{id:1} console.log(self);//{id:1} console.log('id: ', self.id);//id: 1 }.bind(this),500); } fun.call({id:001});
function fun(){ /*setTimeout(() =>{ console.log("args:",arguments); //args:[2,2,3,4] },500);*/ setTimeout(function(){ console.log("args:",arguments); // },500); } fun(2,2,3,4);
这段代码中,箭头函数没有绑定arguments,所以它会取fun的arguments。
普通函数中的this:
1.默认情况下(非严格模式),没有找到直接调用者,this指向window
2.严格模式('use strict'),没有找到直接调用者,this是undefined
3.this总是代表它的直接调用者,比如:obj.fun,那么fun中的this是obj
4.使用call,apply,bind绑定的this指向的是绑定的对象
引用:https://www.cnblogs.com/freelyflying/p/6978126.html
https://www.cnblogs.com/vajoy/p/4902935.html