[乐意黎]IE 10 不支持 let 和箭头函数

如题,由于后面维护修改了之前的某些JS 文件,导致  网页在 IE10下抛错。 折腾了半天,才研究明白。

鉴于此,把 let 修改为 var , 把 箭头函数修改为普通的 function name(){}函数。
如图:


 


ECMAScript 2015(ECMAScript 6) 新特性
 

1. ES2015(ES6) 新增加了两个重要的 JavaScript 关键字:  块级作用域的letconst

2. ES6中的箭头函数  => 箭头最神奇的地方在于他会让你写正确的代码。

下面介绍箭头函数
比如,this在上下文和函数中的值应当是相同的,它不会变化,通常变化的原因都是因为你创建了闭包。

使用箭头函数可以让我们不再用that = this或者self = this或者_this = this或者.bind(this)这样的代码,比如,这些代码在ES5中就特别丑。

var _this = this
$('.btn').click(function(event){
  _this.sendData()
})

这是在ES6中去掉_this = this之后:

$('.btn').click((event) =>{
  this.sendData();
})

可惜的是,ES6委员会觉得再加上瘦箭头(-&>)的话就对我们太好了,所以他们留下了一个老旧的function。(瘦箭头在CoffeeScript中的作用就像ES5/6中一样)

var logUpperCase = function() {
  var _this = this
  this.string = this.string.toUpperCase()
  return function () {
    return console.log(_this.string)
  }
}

logUpperCase.call({ string: 'es6 rocks' })();
//ES6 ROCKS

在ES6中我们无需_this

var logUpperCase = function() {
  this.string = this.string.toUpperCase()
  return () => console.log(this.string)
}

logUpperCase.call({ string: 'es6 rocks' })();

//ES6 ROCKS

注意,在ES6中你可以合理的把箭头函数和旧式 function 函数混用。当箭头函数所在语句只有一行时,它就会变成一个表达式,它会直接返回这个语句的值。但是如果你有多行语句,你就要明确的使用return

这是ES5中利用messages数组创建一个数组的代码:

var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']

var messages = ids.map(function (value) {
  return 'ID is ' + value // 显式返回
});

//["ID is 5632953c4e345e145fdf2df8", "ID is 563295464e345e145fdf2df9"]

在ES6中会变成这样:

var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map(value => `ID is ${value}`) // 隐式返回

//["ID is 5632953c4e345e145fdf2df8", "ID is 563295464e345e145fdf2df9"]

注意到我用了字符串模版吗,又一个从CoffeeScript中来的功能,我爱它们!

在只有一个参数的函数签名中,括号是可有可无的,但是如果多于一个参数时就要加上。

var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
// 隐式返回
var messages = ids.map((value, index, list) => `ID of ${index} element is ${value} `) 

//  ["ID of 0 element is 5632953c4e345e145fdf2df8 ", "ID of 1 element is 563295464e345e145fdf2df9 "]

乐意黎

发布了423 篇原创文章 · 获赞 391 · 访问量 906万+

猜你喜欢

转载自blog.csdn.net/aerchi/article/details/90234419