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指向问题
普通函数指向调用处,箭头函数指向定义处

  1. 普通函数的this 指向调用它的那个对象,例如 obj.func ,那么func中的this就是obj
  2. 箭头函数不能作为构造函数,不能使用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{}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值