ReactNativeReactNative系列React Native开发

JS箭头函数与传统JavaScript函数使用与区别

2017-09-11  本文已影响70人  jiaming_
箭头函数的特性:

有这些这些差异的原因:对this的绑定是JavaScript错误的常见来源之一。容易丢失函数内置数值,或得出意外结果。其次,将箭头函数限制为使用固定this引用,有利于JavaScript引擎优化处理。

常见使用:
//箭头函数返回单个值(当入参是一个不需要加())
var getItem=key=>value;
//返回运算表达式结果
var sum=(n1,n2)=>n1+n2;
//返回运算表达式结果
var sum2=()=>1+1;
//大括号函数体
var sum3=(n1,n2)=>{return n1+n2;}
//箭头函数返回对象
var getItem2=key=>({
    id:key,
    name:'jm'
})

使用普通的function声明函数:
var Comp = {
   id='123' ,
   init:function(){
       document.addEventListener("click", function(event) {
            this.doSomething(event.type); // error
        }, false);
   },
   doSomething:function(type){
             console.log("Handling " + type + " for " + this.id);
   }
}

这里,因为函数内部this关联问题,this会根据当前函数执行环境去取值,所以this.doSomething(event.type); 这里的this会指向全局对象,全局对象没有doSomething方法,就undefinde了。

解决:
这里在函数中使用bind()将this与Comp明确关联起来,相当于又创建一个已关联现有this的新函数,即可解决问题。

var Comp = {
   id='123' ,
   init:function(){
       document.addEventListener("click", (function(event) {
            this.doSomething(event.type); // error
        }).bind(this), false);
   },
   doSomething:function(type){
             console.log("Handling " + type + " for " + this.id);
   }
}

当然,由于前面所述箭头函数内置的this的值,取决于箭头函数在哪定义,而非箭头函数执行的上下文环境。
这里将function声明的函数替换为箭头函数,即可直接使用this.doSomething()了。

var Comp = {
   id='123' ,
   init:function(){
       document.addEventListener("click", ()=>this.doSomething(), false);
   },
   doSomething:function(type){
             console.log("Handling " + type + " for " + this.id);
   }
}

当然,箭头函数的声明方式也就决定了其简练性,使得代码直观,简单,值得去使用。

其他:

参考:http://www.jb51.net/article/50770.htm

上一篇 下一篇

猜你喜欢

热点阅读