关键字: 函数都是对象
js
中函数都是Function
对象,它们也具有属性和方法,最为特殊的是它们可以被调用。
function fn() {}
typeof(xxx)
// "function"
fn instanceof Function
// True
关键字: Function
的属性、方法
-
arguments
arguments
可以获得函数中的参数。arguments
对象不是一个Array
,它只具有索引值和length
function fn() { console.log(arguments); console.log(arguments.length); console.log(typeof arguments); console.log(arguments instanceof Array); } fn(1, 2, 3); // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ] // 3 // object // false
有两种方法可以将
arguments
转换成Array
var args = Array.from(arguments); var args = [...arguments];
arguments
有一个callee
属性,这个属性的值是当前的执行函数
注意点:当函数包含剩余参数、默认参数、解构赋值时,arguments
不会跟踪参数,只反应函数调用时提供的参数function fn(a) { arguments[0] = 10; console.log(a); } fn(0); // 10 function fn(a = 1) { arguments[0] = 10; console.log(a); } fn(0); // 0
-
函数的调用
Function.prototype.apply()
/Function.prototype.call()
/Function.prototype.bind()
Function.prototype.apply()
: 参数以数组形式传入
Function.prototype.call()
: 参数以参数列表形式传入
Function.prototype.bind()
: 绑定函数运行上下文,返回新函数详细说明:
最传统常见的函数调用方法:function fn() { console.log('fn is called'); } fn(); // "fn is called"
使用
apply
/call
function fn() { console.log('fn is called'); } fn.apply(); // "fn is called" fn.call(); // "fn is called"
为什么函数也能这样调用呢?上文提到所有函数的原型对象都是
Function
(fn.__proto__ === Function.prototype
),这里调用的都是Function.prototype
上的方法。
apply
/call
区别
apply
/call
接受参数不同。call
接受多个参数,第一个参数是函数绑定的执行上下文环境,后面接受传参;apply
只接受两个
参数,第一个参数是函数绑定的执行上下文环境,后面通过一个数组或类数组接受传参。bind
方法可以改变函数上下文执行环境,特别的是bind()
会创建一个新函数(称为绑定函数)而且这个函数的函数体和原函数是一样的,所以bind
方法的执行结果是返回一个函数。
bind()
函数接收第一个参数是绑定的上下文环境,后续参数为接受传参- 应用一,改变
this
const a = 'out of obj'; const obj = { a: 'in obj', fn() { return this.a; }, }; obj.fn(); // 'in obj' obj.fn.bind(this); // return obj.fn const outfn = obj.fn.bind(this); outfn(); // 'out of obj'
- 应用二,传入预设参数
function cost() { return `${arguments[0]} ${arguments[1]}`; } const costWithCny = cost.bind(undefined, 'CNY'); const costWithUsd = cost.bind(undefined, 'USD'); costWithCny(10); // 'CNY 10' costWithUsd(10); // 'USD 10'
- 应用一,改变
网友评论