您的位置:首页 > Web前端 > JavaScript

再不用ES6就Out了--函数的新特性

2016-11-29 18:43 267 查看

函数默认值

默认值这要是针对参数传入为undefined的值。ES6之前的写法:

function add(x, y) {
x = x || 1;
y = y || 1;
return x + y;
}
console.log(add()); // 2


进入ES6的你:

function add(x = 1, y = x) {
return x + y;
}
console.log(add()); // 2


这里有一点要注意的:(函数内不能再重新声明参数变量)

function add(x = 1, y = 1) {
let x = 20; //Error
const y = 20; //Error
}


rest参数

说到rest参数,首先介绍一下新的运算符,扩展运算符(…)

* 将一个数组变为参数数列。

let arr = [1,2,3];
console.log(Object.prototype.toString.call(...arr)); //[object Number]这点有点奇怪
console.log(...arr); //1 2 3


怎么用扩展运算符来成就rest参数呢:

function add(...numbers) {
let sum = 0;
for (let val of numbers) {
sum += val;
}
return sum;
}
let arr = [1,2,3,4,5];
console.log(add(1,2,3,4,5)); //15
console.log(add(...arr)); //15
//ES5的写法
console.log(add.apply(null,arr)); //15


注意事项:

* rest参数只能是最后一个参数(剩下的参数的意思)

* 使用rest参数代替arguments

箭头函数

ES6之前的写法:

function add(x, y) {
return x + y;
}


进入ES6你可以采用这样的姿势:

单个参数 单条语句
let add = n => n * 10;

多个参数,多条语句
let add = (x = 1, y = x) => {
x = x * 10;
y = y - 10;
return x * y;
}


是不是简洁明了。接下来让我们来看一段代码更深入的了解箭头函数:

ES6之前:
function old() {
function temp() {
console.log('==========old============');
console.log(this); // window
console.log(this.name) //global
}
temp();
}
var name = 'global';
old.call({name: 'xiaoming'});

ES6:
let newFunc = function () {
let temp = () => {
console.log("=========new===========");
console.log(this); //Object {name: "xiaoming"}
console.log(this.name); //xiaoming
}
temp();
}
var name = 'global';
newFunc.call({name: 'xiaoming'});


这里我们发现箭头函数是可以绑定this的,它是怎么实现的呢?

var newFunc = function () {
var _this = this; //保存this
var temp = function () {
console.log("=========polyfill===========");
console.log(_this); //Object {name: "xiaoming"}
console.log(_this.name); //xiaoming
}
temp();
}

var name = 'global'; //Object {name: "xiaoming"}
newFunc.call({name: 'xiaoming'}); //xiaoming


所以箭头函数本身是没有this的,而是绑定了this。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript es6