函数是Javascript 中很重要的对象,JS 提供三种方式实现函数。
1. function 关键字
1.1 定义function 函数
function student() {
this.name = 'spursy';
this.age = 20;
}
var stu = new student();
console.log(stu instanceof student); // true
console.log(typeof(student)); // function
console.log(typeof(stu)); // object
1.2 自定义匿名类
var stu = new function() {
this.name = 'spursy';
this.age = 20;
};
console.log(typeof(stu)); // object
2. 系统内置函数对象(Function)来构建一个函数
/**
* Demo 1
*/
let str = 'return ' + '` This is ${name}.`';
let fun = new Function('name', str);
var result = fun("Spursy");
console.log(result); // This is Spursy.
/**
* Demo 2
*/
let str = '(name) => ` This is ${name}.`';
let fun = eval.call(null, str);
var result = fun("Spursy");
console.log(result); // This is Spursy.
3. ES6 箭头函数(arrow function)
var numbers = [1,3,5,7,9];
var result = numbers.map((number) => number * 3);
console.log(result); // [3, 9, 15, 21, 27]
ES6的箭头函数省略了 function 关键字,并在参数后面添加了 ‘=>’.
(async() => {
await result.total3(); // 箭头函数与async/ await 的结合
})
箭头函数不绑定this
a. 由于 this 已经在词法层面完成了绑定,通过 call() 或 apply() 方法调用一个函数时,只是传入了参数而已,对 this 并没有什么影响。
b. 在箭头函数内部使用 var that = this, debug 发现 that 指向为undefined。
var adder = {
base : 1,
add : function(a) {
var f = v => v + this.base;
return f(a);
},
addThruCall: function(a) {
var f = v => v + this.base;
var b = {
base : 2
};
return f.call(b, a);
}
};
console.log(adder.add(1)); // 输出 2
console.log(adder.addThruCall(1)); // 仍然输出 2(而不是3 ——译者注)
function multiply (x, y) {
return x * y;
}
var result = {
value: 3,
total: () =>
{
var that = this; // that 指向undefined
that.value = multiply(that.value, that.value);
}
};
(async() => {
await result.total3();
})