导航
// 只有一个参数
var f = a => a;
var f = function(a) {
return a;
};
var f = () => 1;
function f() {
return 1;
}
let f = (a, b) => {
return a + b;
};
const full = ({first, last} = {}) => first + ' ' + last;
console.log(full({first: 3, last: 5})); // 35
var arr = [123,4,55,6,7,67,4,56,34,3,54,666,3,7];
var arr1 = arr.sort((a, b) => a - b);
console.log(arr1);
var B = () => {
value:1;
}
var b = new B(); //-->TypeError: B is not a constructor
var sum = (a, b) => {
console.log(arguments);
return a + b;
}
sum(1, 3);
var sum = (...args) => {
console.log(args);
console.log(args[0] + args[1]);
}
sum(1, 2);
let fn = (a, b, ...c) => {
console.log(a, b, c);
}
fn(1, 2, 3, 4, 5);
function foo(x, y, z) {
console.log(x, y, z);
}
foo(...[1, 2, 3]);
let a = [2, 3, 4];
let b = [1, ...a, 5];
console.log(b); // [1, 2, 3, 4, 5]
console.log(function (a) {}.length);
console.log(function (...a) {}.length);
console.log(function (b, c, ...a) {}.length);
function foo() {
console.log(this);
return (a) => {
console.log(this.a);
}
}
var obj1 = {a: 2};
var obj2 = {a: 3};
var bar = foo.call(obj1); // obj1
bar.call(obj2); // 2
// 1. foo.call(obj1); 显示绑定了foo函数的this指向为obj1
// 2. bar.call(obj2); bar是箭头函数,无法显式绑定this
// 3. 箭头函数中的this还是外层作用域的obj1
而返回普通函数则会变更
function foo() {
console.log(this);
return function(a) {
console.log(this.a);
}
}
var obj1 = {a: 2};
var obj2 = {a: 3};
var bar = foo.call(obj1); // obj1
bar.call(obj2); // 3
const person = {
eat() {
console.log(this);
},
drink: () => {
console.log(this);
}
}
person.eat(); // person
person.drink(); // window
// drink箭头函数默认this为window,
// person隐式调用不会改变箭头函数this指向
function foo() {
return () => {
return () => {
return () => {
console.log('id', this.id);
}
}
}
}
var f = foo.call({id: 1}); // foo的this: {id: 1}
var f1 = f.call({id: 2})()(); // 'id' 1
var f2 = f().call({id: 3})(); // 'id' 1
var f3 = f()().call({id: 4}); // 'id' 1
function foo() {
console.log(arguments);
setTimeout(() => {
console.log(arguments);
});
}
foo(1,2,3,4,5);
// setTimeout箭头函数中能打印arguments,但打印的是外层foo中的
// arguments
var a = () => {
return 1;
}
function b() {
return 2;
}
console.log(a.prototype); //-->undefined
console.log(b.prototype); //-->object{...}
function insert(value) {
return {
into(array) {
return {
after(afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}
}
}
}
}
console.log(insert(5).into([1,2,3,4,6,7,8,9]).after(4));
let insert = (value) => ({
into: (array) => ({
after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}
})
})
console.log(insert(5).into([1,2,3,4,6,7,8]).after(4));
var args = Array.prototype.slice.call(arguments)
function sortNumber() {
return Array.prototype.slice.call(arguments).sort(function(a, b) {
return a - b;
});
}
// 改造
const sortNumber = (...args) => args.sort((a, b) => a - b);
函数声明,执行语句比较多,还需要用到递归,需要引用函数名,事件绑定,解绑定