标签:默认值 lin 需要 and als 特性 button 正是 eth
参数的默认值
ES6 允许为函数的参数设置默认值,即直接写在参数定义的后面
函数不能有同名参数
参数初始化会形成一个单独作用域。实际执行的是 let a = 1;
参数默认值是惰性求值的
每次调用函数foo
,都会重新计算x + 1
,而不是默认p
等于 100
let x = 99; function foo(p = x + 1) { console.log(p); } foo(); // 100 x = 100; foo(); // 101
function log(x, y = ‘World‘) { console.log(x, y); } log(‘Hello‘); // Hello World log(‘Hello‘, ‘China‘); // Hello China log(‘Hello‘, ‘‘); // Hello
function Point(x = 0, y = 0) { this.x = x; this.y = y; } const p = new Point(); console.log(p); // { x: 0, y: 0 }
3
3
3
3
rest 多余实参数组
...args x, ...args
...数组名 实参, 多余参数数组
实参列表,是一个真数组
用于获取函数的多余参数
push
方法的例子function push(arr, ...items) { items.forEach(function(item) { arr.push(item); console.log(item); }); }; var arr = []; push(arr, 1, 2, 3)
length
属性,不包括 rest 参数,因为 rest 参数表示 多余的实参列表console.log((function(a) {}).length); // 1 console.log((function(...a) {}).length); // 0 console.log((function(a, ...b) {}).length); // 1
箭头函数 const func = () => {};
简化原来的 const func = function(){};
箭头函数 没有自己的显式原型属性,即 func.prototype = undefined;
箭头函数 不能作为构造函数使用,即不能 new 调用
箭头函数 的 this 指向最近的包裹函数的 this 一致,如果没有函数包裹,则 this 指向 window
箭头函数 可以让 this
指向固定化,这种特性很有利于封装回调函数
实际原因是箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。
正是因为它没有 this,所以也就不能用作构造函数
于箭头函数没有自己的 this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向
其实箭头函数也没有 arguments
、super
、new.target
箭头函数的函数体内 不可以使用 arguments 对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替
不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数
var handler = { id: ‘123456‘, init: function() { document.addEventListener(‘click‘, event => this.doSomething(event.type), false); }, doSomething: function(type) { console.log(‘Handling ‘ + type + ‘ for ‘ + this.id); } };
const func = (x) => {};
const func = x => {};
const func = x => { x += 1;};
const func = x => x+=1;
let getTempItem = id => ({ id: id, name: "Temp" });
// 正常函数写法 [1,2,3].map(function (x) { return x * x; }); // 箭头函数写法 [1,2,3].map(x => x * x);
rest 参数 与 箭头函数的结合使用
const numbers = (...nums) => nums; numbers(1, 2, 3, 4, 5); // [1,2,3,4,5] const headAndTail = (head, ...tail) => [head, tail]; headAndTail(1, 2, 3, 4, 5); // [1,[2,3,4,5]]
定义函数的方法,且该方法内部包括 this
const cat = { lives: 9, jumps: () => { this.lives--; // this 指向 window ,所以结果肯定是有问题的 }; };
需要动态this
的时候,也不应使用箭头函数
var button = document.getElementById(‘press‘); button.addEventListener(‘click‘, () => { this.classList.toggle(‘on‘); });
3
3
3
33
3
3
3
3
3
3
标签:默认值 lin 需要 and als 特性 button 正是 eth
原文地址:https://www.cnblogs.com/tianxiaxuange/p/10122880.html