js箭头函数和普通函数的区别
借鉴: https://www.cnblogs.com/biubiuxixiya/p/8610594.html 阮一峰 http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html 普通函数this:https://www.cnblogs.com/watermelons/p/11510443.html
主要区别在this指向问题 普通函数指向调用处,箭头函数指向定义处
- 普通函数的this 指向调用它的那个对象,例如 obj.func ,那么func中的this就是obj
- 箭头函数不能作为构造函数,不能使用new,没有this,arguments箭头函数,箭头函数的this永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply()(或者说箭头函数中的this指向的是定义时的this,而不是执行时的this
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
console.log(this.name); // My Object
return function(){
return this.name; // The Window
};
},
b: () => {
return this.name; // the window
},
c: function() {
return () => {
return this.name; //My Object
}
}
}
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a);
console.log(this);
}
}
}
var j = o.b.fn;
j(); // undefined window
o.b.fn();//12 b{}
下一篇:
解决xshell连接不上虚拟机
