Function properties and methods
In JavaScript, functions are first-class citizens. They can not only be invoked but also possess properties and methods. As objects, functions can have properties dynamically added and their behavior or context altered through built-in methods. Understanding these features is crucial for writing flexible and efficient code.
Function Properties
name Property
The name
property of a function returns the name it was declared with. Anonymous functions or arrow functions infer their names based on context:
function greet() {}
console.log(greet.name); // "greet"
const sayHi = function() {};
console.log(sayHi.name); // "sayHi"
const arrow = () => {};
console.log(arrow.name); // "arrow"
length Property
length
indicates the number of formal parameters defined in the function, excluding default parameters or rest parameters:
function sum(a, b, c = 10) {}
console.log(sum.length); // 2
function merge(...args) {}
console.log(merge.length); // 0
prototype Property
Constructor functions use prototype
to implement inheritance:
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
console.log(this.name);
};
const john = new Person('John');
john.sayName(); // "John"
caller Property
In non-strict mode, caller
returns a reference to the function that invoked the current function:
function outer() {
inner();
}
function inner() {
console.log(inner.caller); // Outputs the outer function body
}
outer();
Function Methods
call() and apply()
Change the this
binding when the function is executed. call
accepts an argument list, while apply
accepts an array:
const obj = { value: 10 };
function multiply(n, m) {
return this.value * n * m;
}
console.log(multiply.call(obj, 2, 3)); // 60
console.log(multiply.apply(obj, [2, 3])); // 60
bind()
Creates a new function with a permanently bound this
value and supports currying:
const module = {
x: 42,
getX: function() { return this.x; }
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); // 42
// Currying example
function add(a, b) {
return a + b;
}
const add5 = add.bind(null, 5);
console.log(add5(3)); // 8
toString()
Returns the function's source code as a string, including comments and whitespace:
function foo() {
// This is a test function
return 'bar';
}
console.log(foo.toString());
// Outputs the complete function definition:
// "function foo() {
// // This is a test function
// return 'bar';
// }"
Custom Function Properties
Functions, as objects, can have custom properties added to implement features like state memorization:
function counter() {
counter.count = (counter.count || 0) + 1;
return counter.count;
}
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter.count); // 2
Higher-Order Function Features
Functions as Arguments
function operate(num, operation) {
return operation(num);
}
function double(x) { return x * 2; }
function square(x) { return x * x; }
console.log(operate(5, double)); // 10
console.log(operate(5, square)); // 25
Functions Returning Functions
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const triple = createMultiplier(3);
console.log(triple(7)); // 21
Arrow Function Specifics
Arrow functions do not have their own this
, arguments
, super
, or new.target
bindings:
const obj = {
value: 1,
regular: function() {
return this.value;
},
arrow: () => this.value
};
console.log(obj.regular()); // 1
console.log(obj.arrow()); // undefined
Function Arguments Object
arguments Object
Traditional functions can access an array-like arguments
object internally:
function logArgs() {
console.log(arguments.length);
console.log(arguments[0]);
}
logArgs(1, 2, 3); // Outputs 3 and 1
Rest Parameters
ES6 introduced rest parameters, which are true arrays:
function sum(...numbers) {
return numbers.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3)); // 6
Immediately Invoked Function Expressions (IIFE)
A common pattern for creating isolated scopes:
(function() {
const privateVar = 'secret';
console.log(privateVar); // "secret"
})();
// IIFE with parameters
(function(message) {
console.log(message); // "Hello"
})('Hello');
Function Caching Optimization
Using function properties to implement memoization:
function fibonacci(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 2) return 1;
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
return memo[n];
}
console.log(fibonacci(50)); // 12586269025
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:立即执行函数(IIFE)
下一篇:函数柯里化