Fungsi JavaScript ialah blok kod yang direka untuk melaksanakan tugas tertentu.
Fungsi JavaScript dilaksanakan apabila "sesuatu" memanggilnya (memanggilnya).
Fungsi JavaScript ialah konsep asas dalam bahasa, membolehkan anda merangkum kod ke dalam blok boleh guna semula. Berikut ialah gambaran keseluruhan:
Ini ialah cara yang paling biasa untuk menentukan fungsi. Anda menggunakan kata kunci fungsi diikuti dengan nama dan blok kod.
function greet(name) { return `Hello, ${name}!`; } console.log(greet('Alice')); // Outputs: Hello, Alice!
Fungsi juga boleh ditakrifkan sebagai ungkapan dan diberikan kepada pembolehubah. Ini boleh berguna untuk mencipta fungsi tanpa nama atau apabila anda ingin menyampaikan fungsi sebagai argumen.
const greet = function(name) { return `Hello, ${name}!`; }; console.log(greet('Bob')); // Outputs: Hello, Bob!
Diperkenalkan dalam ES6, fungsi anak panah menawarkan sintaks yang lebih pendek. Ia amat berguna untuk fungsi sebaris dan mempunyai gelagat yang berbeza untuk kata kunci ini.
const greet = (name) => `Hello, ${name}!`; console.log(greet('Charlie')); // Outputs: Hello, Charlie!
Anda boleh memberikan nilai lalai untuk parameter fungsi, yang akan digunakan jika tiada nilai atau undefined diluluskan.
function greet(name = 'Guest') { return `Hello, ${name}!`; } console.log(greet()); // Outputs: Hello, Guest! console.log(greet('Dana')); // Outputs: Hello, Dana!
Sintaks ... membolehkan anda mewakili bilangan argumen yang tidak ditentukan sebagai tatasusunan.
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3)); // Outputs: 6 console.log(sum(1, 2, 3, 4, 5)); // Outputs: 15
Fungsi dalam JavaScript mempunyai skopnya sendiri. Pembolehubah yang diisytiharkan di dalam fungsi tidak boleh diakses dari luar.
function example() { let localVar = 'I am local'; console.log(localVar); // Outputs: I am local } console.log(localVar); // ReferenceError: localVar is not defined
Fungsi boleh mengembalikan nilai menggunakan kata kunci pulangan. Jika tiada pernyataan pemulangan digunakan, fungsi itu kembali tidak ditentukan secara lalai.
function add(a, b) { return a + b; } console.log(add(5, 3)); // Outputs: 8
IIFE ialah fungsi yang berjalan sebaik sahaja ia ditakrifkan. Ia sering digunakan untuk mencipta skop baharu.
(function() { console.log('I am an IIFE'); })();
Walaupun tidak biasa digunakan, anda boleh mencipta fungsi menggunakan pembina Fungsi.
const greet = new Function('name', 'return `Hello, ${name}!`'); console.log(greet('Eve')); // Outputs: Hello, Eve!
Penutupan ialah fungsi yang mempunyai akses kepada pembolehubah daripada skop fungsi lain. Ini ialah ciri hebat dalam JavaScript.
function makeCounter() { let count = 0; return function() { count += 1; return count; }; } const counter = makeCounter(); console.log(counter()); // Outputs: 1 console.log(counter()); // Outputs: 2
Jangan ragu untuk menyelami lebih mendalam mana-mana konsep ini atau tanya jika anda mempunyai soalan khusus!
Fungsi JavaScript mempunyai pelbagai sintaks, setiap satu berguna dalam konteks yang berbeza. Berikut ialah gambaran keseluruhan terperinci:
Parameter fungsi JavaScript mentakrifkan nilai yang boleh diterima oleh fungsi apabila ia dipanggil. Parameter ini membolehkan fungsi menjadi lebih fleksibel dan boleh digunakan semula. Berikut ialah pandangan terperinci tentang pelbagai aspek parameter fungsi JavaScript:
Apabila mentakrifkan fungsi, anda menentukan parameter dalam definisi fungsi. Apabila fungsi dipanggil, anda memberikan hujah yang sepadan dengan parameter ini.
Contoh:
function greet(name, age) { console.log(`Hello, ${name}! You are ${age} years old.`); } greet('Alice', 30); // Outputs: Hello, Alice! You are 30 years old.
Anda boleh menetapkan nilai lalai kepada parameter. Jika tiada nilai atau undefined diluluskan untuk parameter ini, nilai lalai akan digunakan.
Contoh:
function greet(name = 'Guest', age = 18) { console.log(`Hello, ${name}! You are ${age} years old.`); } greet(); // Outputs: Hello, Guest! You are 18 years old. greet('Bob'); // Outputs: Hello, Bob! You are 18 years old. greet('Charlie', 25); // Outputs: Hello, Charlie! You are 25 years old.
Parameter rehat membolehkan anda mewakili bilangan argumen yang tidak ditentukan sebagai tatasusunan. Ini berguna apabila anda tidak tahu berapa banyak hujah yang akan diluluskan.
Contoh:
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3)); // Outputs: 6 console.log(sum(1, 2, 3, 4, 5)); // Outputs: 15
Penstrukturan membolehkan anda membongkar nilai daripada tatasusunan atau sifat daripada objek ke dalam pembolehubah berbeza secara terus dalam parameter fungsi.
Contoh dengan Pemusnahan Objek:
function displayInfo({ name, age }) { console.log(`Name: ${name}, Age: ${age}`); } const person = { name: 'Alice', age: 30 }; displayInfo(person); // Outputs: Name: Alice, Age: 30
Contoh dengan Pemusnahan Tatasusunan:
function sum([a, b]) { return a + b; } console.log(sum([5, 10])); // Outputs: 15
Apabila menggunakan kedua-dua parameter biasa dan parameter rehat, parameter rehat mestilah parameter terakhir dalam definisi fungsi.
Contoh:
function logInfo(name, age, ...additionalInfo) { console.log(`Name: ${name}, Age: ${age}`); console.log('Additional Info:', additionalInfo); } logInfo('Alice', 30, 'Engineer', 'Loves JavaScript'); // Outputs: // Name: Alice, Age: 30 // Additional Info: ['Engineer', 'Loves JavaScript']
Menggunakan objek sebagai parameter membolehkan anda menghantar argumen bernama. Ini amat berguna untuk fungsi dengan banyak parameter atau parameter pilihan.
Contoh:
function createProfile({ name, age, job }) { console.log(`Name: ${name}, Age: ${age}, Job: ${job}`); } createProfile({ name: 'Alice', age: 30, job: 'Developer' }); // Outputs: Name: Alice, Age: 30, Job: Developer
JavaScript does not support function overloading in the traditional sense (same function name with different parameter lists). Instead, you can handle different parameter scenarios inside a function.
Example:
function process(value1, value2) { if (value2 === undefined) { console.log(`Processing single value: ${value1}`); } else { console.log(`Processing two values: ${value1} and ${value2}`); } } process(5); // Outputs: Processing single value: 5 process(5, 10); // Outputs: Processing two values: 5 and 10
In non-arrow functions, the arguments object provides access to all the arguments passed to a function. It is an array-like object but does not have array methods.
Example:
function printArguments() { for (let i = 0; i < arguments.length; i++) { console.log(arguments[i]); } } printArguments('a', 'b', 'c'); // Outputs: // a // b // c
This is the standard way to invoke a function by simply calling its name followed by parentheses.
Example:
function greet(name) { console.log(`Hello, ${name}!`); } greet('Alice'); // Outputs: Hello, Alice!
When a function is a property of an object, it's called a method. You invoke it using dot notation or bracket notation.
Example:
const person = { name: 'Bob', greet: function() { console.log(`Hello, ${this.name}!`); } }; person.greet(); // Outputs: Hello, Bob!
Functions invoked with the new keyword act as constructors and create new instances of objects. In this case, this refers to the newly created object.
Example:
function Person(name) { this.name = name; } const person1 = new Person('Charlie'); console.log(person1.name); // Outputs: Charlie
The call and apply methods allow you to invoke a function with a specific this context and arguments.
call Method: Passes arguments separately.
Example:
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name}${punctuation}`); } const person = { name: 'Dana' }; greet.call(person, 'Hello', '!'); // Outputs: Hello, Dana!
apply Method: Passes arguments as an array.
Example:
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name}${punctuation}`); } const person = { name: 'Eva' }; greet.apply(person, ['Hi', '.']); // Outputs: Hi, Eva.
Arrow functions do not have their own this context; they inherit this from the surrounding scope.
Example:
const person = { name: 'Frank', greet: () => { console.log(`Hello, ${this.name}!`); // 'this' refers to the surrounding scope, not the 'person' object } }; person.greet(); // Outputs: Hello, undefined!
The bind method creates a new function with a specific this context and optional arguments.
Example:
function greet(greeting) { console.log(`${greeting}, ${this.name}!`); } const person = { name: 'Grace' }; const greetPerson = greet.bind(person, 'Welcome'); greetPerson(); // Outputs: Welcome, Grace!
An IIFE is a function expression that is immediately executed after its definition.
Example:
(function() { console.log('I am an IIFE!'); })(); // Outputs: I am an IIFE!
JavaScript functions can be dynamically invoked using the Function constructor or the eval function, though these approaches are less common and generally discouraged due to security and performance concerns.
Example Using Function Constructor:
const dynamicFunc = new Function('a', 'b', 'return a + b;'); console.log(dynamicFunc(2, 3)); // Outputs: 5
Example Using eval:
const code = 'console.log("Hello from eval!")'; eval(code); // Outputs: Hello from eval!
In JavaScript, a function's return statement is crucial for specifying the output or result of the function. Here’s a detailed look at how return works and its various nuances:
A function can return a value using the return statement. When the return statement is executed, the function terminates, and the specified value is sent back to the caller.
Example:
function add(a, b) { return a + b; } const result = add(5, 3); console.log(result); // Outputs: 8
A function can use return to exit early before reaching the end of its block. This is often used to handle special cases or invalid inputs.
Example:
function divide(a, b) { if (b === 0) { return 'Error: Division by zero'; } return a / b; } console.log(divide(10, 2)); // Outputs: 5 console.log(divide(10, 0)); // Outputs: Error: Division by zero
In arrow functions with a single expression, the return keyword can be omitted. The expression is automatically returned.
Example:
const multiply = (a, b) => a * b; console.log(multiply(4, 5)); // Outputs: 20
JavaScript functions can only return one value. However, you can return multiple values by using an object or array.
Using an Object:
function getPerson() { return { name: 'Alice', age: 30 }; } const person = getPerson(); console.log(person.name); // Outputs: Alice console.log(person.age); // Outputs: 30
Using an Array:
function getCoordinates() { return [40.7128, -74.0060]; // latitude and longitude } const [latitude, longitude] = getCoordinates(); console.log(latitude); // Outputs: 40.7128 console.log(longitude); // Outputs: -74.0060
If a function does not have a return statement, or if the return statement does not specify a value, the function returns undefined.
Example:
function greet(name) { console.log(`Hello, ${name}!`); // No return statement } const result = greet('Bob'); console.log(result); // Outputs: undefined
In recursive functions, the return statement is used to return values at each level of recursion.
Example:
function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); } console.log(factorial(5)); // Outputs: 120
When using constructors (functions invoked with new), the return statement can be used to return a different object. If no return statement is provided, the newly created instance is returned by default.
Example:
function Person(name) { this.name = name; // Optional return statement // return { name: name }; // This would override the default instance } const person = new Person('Alice'); console.log(person.name); // Outputs: Alice
Functions within closures can return values that depend on variables from their outer function.
Example:
function createCounter() { let count = 0; return function() { count += 1; return count; }; } const counter = createCounter(); console.log(counter()); // Outputs: 1 console.log(counter()); // Outputs: 2
In JavaScript, functions can be assigned to variables, which allows them to be treated as first-class objects. This means functions can be passed around as values, stored in variables, and used in various ways. Here’s a comprehensive look at how functions can be used as variable values:
You can assign a function to a variable, effectively creating a function expression.
Example:
const greet = function(name) { return `Hello, ${name}!`; }; console.log(greet('Alice')); // Outputs: Hello, Alice!
In this example, greet is a variable that holds a function. The function can be called using greet().
Function expressions are functions that are defined inside expressions and can be assigned to variables.
Example:
const add = function(a, b) { return a + b; }; console.log(add(2, 3)); // Outputs: 5
Arrow functions provide a concise syntax and can also be assigned to variables.
Example:
const multiply = (x, y) => x * y; console.log(multiply(4, 5)); // Outputs: 20
Functions assigned to variables can be passed as arguments to other functions. This is a common pattern in JavaScript.
Example:
function executeFunction(fn, value) { return fn(value); } const double = x => x * 2; console.log(executeFunction(double, 5)); // Outputs: 10
Functions can return other functions. This technique is used in functional programming and closures.
Example:
function createMultiplier(factor) { return function(x) { return x * factor; }; } const double = createMultiplier(2); const triple = createMultiplier(3); console.log(double(5)); // Outputs: 10 console.log(triple(5)); // Outputs: 15
Functions can be stored in arrays and accessed or invoked using array indices.
Example:
const functions = [ function(a) { return a + 1; }, function(a) { return a * 2; }, function(a) { return a - 3; } ]; console.log(functions ); // Outputs: 6 console.log(functions ); // Outputs: 10 console.log(functions ); // Outputs: 2
Functions can be properties of objects and accessed using dot notation or bracket notation.
Example:
const math = { add: function(a, b) { return a + b; }, subtract: function(a, b) { return a - b; } }; console.log(math.add(10, 5)); // Outputs: 15 console.log(math.subtract(10, 5)); // Outputs: 5
In event-driven programming, functions are often assigned to variables and used as event handlers.
Example:
const button = document.getElementById('myButton'); const handleClick = () => { alert('Button clicked!'); }; button.addEventListener('click', handleClick);
Functions assigned to variables can be passed as callbacks to other functions.
Example:
function processArray(arr, callback) { return arr.map(callback); } const numbers = [1, 2, 3, 4, 5]; const squaredNumbers = processArray(numbers, x => x * x); console.log(squaredNumbers); // Outputs: [1, 4, 9, 16, 25]
Functions can be created dynamically and assigned to variables, such as using the Function constructor.
Example:
const createAdder = new Function('a', 'b', 'return a + b;'); console.log(createAdder(2, 3)); // Outputs: 5
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
// code here can NOT use carName function myFunction() { let carName = "Volvo"; // code here CAN use carName } // code here can NOT use carName
In JavaScript, function invocation refers to the various ways a function can be executed. The manner in which a function is invoked affects its behavior, particularly the this context and the function’s scope. Here’s a detailed overview of different methods of function invocation:
The most straightforward way to invoke a function is to call it directly by using its name followed by parentheses.
Example:
function greet(name) { console.log(`Hello, ${name}!`); } greet('Alice'); // Outputs: Hello, Alice!
When a function is a property of an object, it is called a method. It is invoked using the dot notation or bracket notation on the object.
Example:
const person = { name: 'Bob', greet: function() { console.log(`Hello, ${this.name}!`); } }; person.greet(); // Outputs: Hello, Bob!
Functions invoked with the new keyword are treated as constructors. They create a new instance of an object. In this context, this refers to the newly created object.
Example:
function Person(name) { this.name = name; } const person1 = new Person('Charlie'); console.log(person1.name); // Outputs: Charlie
The call() method allows you to invoke a function with a specific this context and individual arguments. It’s useful for borrowing methods from other objects.
Example:
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name}${punctuation}`); } const person = { name: 'Dana' }; greet.call(person, 'Hello', '!'); // Outputs: Hello, Dana!
The apply() method is similar to call(), but it takes arguments as an array. This method is useful when you have an array of arguments that need to be passed to the function.
Example:
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name}${punctuation}`); } const person = { name: 'Eva' }; greet.apply(person, ['Hi', '.']); // Outputs: Hi, Eva.
The bind() method creates a new function with a specific this value and optionally pre-set arguments. This new function can be invoked later.
Example:
function greet(greeting, punctuation) { console.log(`${greeting}, ${this.name}${punctuation}`); } const person = { name: 'Frank' }; const boundGreet = greet.bind(person, 'Welcome'); boundGreet('!'); // Outputs: Welcome, Frank!
An IIFE is a function expression that is immediately executed after its definition. It’s often used to create a new scope to avoid polluting the global namespace.
Example:
(function() { console.log('I am an IIFE!'); })(); // Outputs: I am an IIFE!
Arrow functions are a concise syntax for writing functions and they don’t have their own this. Instead, this is inherited from the surrounding lexical scope.
Example:
const person = { name: 'Grace', greet: () => { console.log(`Hello, ${this.name}!`); // 'this' refers to the surrounding scope, not the 'person' object } }; person.greet(); // Outputs: Hello, undefined!
You can dynamically create functions using the Function constructor, though it is generally less common and less safe due to potential performance and security issues.
Example:
const dynamicFunc = new Function('a', 'b', 'return a + b;'); console.log(dynamicFunc(2, 3)); // Outputs: 5
Functions can be assigned to variables and then invoked. This includes both named and anonymous functions.
Example:
const add = function(a, b) { return a + b; }; console.log(add(2, 3)); // Outputs: 5
The apply() method in JavaScript is used to call a function with a given this value and arguments provided as an array (or an array-like object). It’s part of the Function.prototype and is very useful for invoking functions with a specific context and arguments.
Here’s a detailed breakdown of how apply() works:
func.apply(thisArg, [argsArray])
Suppose you have a function that adds two numbers:
function add(a, b) { return a + b; }
You can use apply() to call this function with a specific this value (though in this simple case, this isn’t used) and an array of arguments:
const result = add.apply(null, [3, 4]); console.log(result); // Outputs: 7
When calling methods on objects, apply() can be used to specify the this value. This is particularly useful for methods that need to be called in the context of a different object.
Example:
const person = { name: 'Alice', greet: function(greeting) { return `${greeting}, ${this.name}!`; } }; const anotherPerson = { name: 'Bob' }; console.log(person.greet.apply(anotherPerson, ['Hello'])); // Outputs: Hello, Bob!
In this example, greet is called on anotherPerson instead of the person object.
apply() is often used with Math methods to pass an array of numbers as individual arguments.
Example:
const numbers = [5, 6, 2, 8, 3]; const maxNumber = Math.max.apply(null, numbers); console.log(maxNumber); // Outputs: 8
In this example, Math.max is called with the numbers in the array spread out as individual arguments.
The call() method is similar to apply(), but it takes arguments individually rather than as an array.
Example with call():
function greet(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`; } const person = { name: 'Charlie' }; console.log(greet.call(person, 'Hi', '!')); // Outputs: Hi, Charlie!
The bind() method in JavaScript is used to create a new function with a specific this context and, optionally, pre-set arguments. This is particularly useful for setting the context of this when passing functions around or for partial function application.
Here’s a detailed overview of how bind() works and how it can be used:
function.bind(thisArg, arg1, arg2, ...)
The most basic use of bind() is to create a new function where this is fixed to a specific value.
function greet(greeting) { console.log(`${greeting}, ${this.name}!`); } const person = { name: 'Alice' }; const boundGreet = greet.bind(person, 'Hello'); boundGreet(); // Outputs: Hello, Alice!
In this example, boundGreet is a new function created by bind() where this is permanently set to the person object.
bind() can also be used for partial application, where you pre-set some arguments and leave others to be provided later.
function multiply(a, b) { return a * b; } const double = multiply.bind(null, 2); console.log(double(5)); // Outputs: 10
In this example, double is a function that multiplies its argument by 2. The bind() method creates this new function by fixing 2 as the first argument.
bind() is particularly useful when dealing with methods that need to be used as callbacks but must retain the correct this context.
Example with Event Handlers:
class Counter { constructor() { this.count = 0; this.increment = this.increment.bind(this); // Fixes 'this' context } increment() { this.count += 1; console.log(this.count); } } const counter = new Counter(); document.getElementById('incrementButton').addEventListener('click', counter.increment);
In this example, increment needs to have the correct this context when called as an event handler. By using bind(), this in increment correctly refers to the Counter instance.
You can also use bind() to fix multiple arguments.
function displayInfo(age, occupation) { console.log(`Name: ${this.name}, Age: ${age}, Occupation: ${occupation}`); } const person = { name: 'Bob' }; const boundDisplayInfo = displayInfo.bind(person, 30); boundDisplayInfo('Engineer'); // Outputs: Name: Bob, Age: 30, Occupation: Engineer
Here, boundDisplayInfo has this set to person and the first argument (age) is pre-set to 30.
While call() and apply() can also set the this context and pass arguments, they invoke the function immediately. bind() creates a new function that, when called, will have its this set to the specified value and will use the provided arguments.
function showInfo(age, occupation) { console.log(`Name: ${this.name}, Age: ${age}, Occupation: ${occupation}`); } const person = { name: 'Charlie' }; showInfo.call(person, 28, 'Teacher'); // Outputs: Name: Charlie, Age: 28, Occupation: Teacher
function showInfo(age, occupation) { console.log(`Name: ${this.name}, Age: ${age}, Occupation: ${occupation}`); } const person = { name: 'Dana' }; showInfo.apply(person, [32, 'Artist']); // Outputs: Name: Dana, Age: 32, Occupation: Artist
function showInfo(age, occupation) { console.log(`Name: ${this.name}, Age: ${age}, Occupation: ${occupation}`); } const person = { name: 'Eva' }; const boundShowInfo = showInfo.bind(person, 40); boundShowInfo('Scientist'); // Outputs: Name: Eva, Age: 40, Occupation: Scientist
In JavaScript, a closure is a powerful concept where a function retains access to its lexical scope even after the function has finished executing. Closures allow functions to access variables from an outer scope that have already executed, which is useful for creating private variables, factory functions, and more.
Here’s a detailed overview of closures:
A closure is created when a function is defined inside another function, and the inner function retains access to the outer function’s variables. This allows the inner function to "close over" the variables of its outer function.
Example:
function outerFunction() { let outerVariable = 'I am from outer function'; function innerFunction() { console.log(outerVariable); // Inner function has access to outerVariable } return innerFunction; } const closureFunction = outerFunction(); closureFunction(); // Outputs: I am from outer function
In this example:
Access to Outer Variables: Closures can access variables from their containing (outer) scope even after the outer function has completed execution.
Encapsulation: Closures can be used to create private variables and methods, which are not directly accessible from outside the closure.
Persistent State: Closures can maintain state across multiple invocations.
1. Private Variables:
Closures are commonly used to create private variables in JavaScript, which are not accessible from outside the closure.
function createCounter() { let count = 0; // Private variable return function() { count += 1; console.log(count); }; } const counter = createCounter(); counter(); // Outputs: 1 counter(); // Outputs: 2 counter(); // Outputs: 3
In this example:
2. Function Factories:
Closures can be used to create factory functions that generate other functions with specific behavior.
function createGreeting(greeting) { return function(name) { console.log(`${greeting}, ${name}!`); }; } const sayHello = createGreeting('Hello'); const sayGoodbye = createGreeting('Goodbye'); sayHello('Alice'); // Outputs: Hello, Alice! sayGoodbye('Bob'); // Outputs: Goodbye, Bob!
In this example:
3. Event Handlers:
Closures are often used in event handlers to preserve context and state.
function setupButton(buttonId) { let clickCount = 0; document.getElementById(buttonId).addEventListener('click', function() { clickCount += 1; console.log(`Button clicked ${clickCount} times`); }); } setupButton('myButton');
In this example:
Closures can sometimes lead to confusion with the this context, especially in object-oriented programming. Arrow functions, which do not have their own this, are often used in conjunction with closures to avoid issues related to this.
Example with Arrow Functions:
function Counter() { this.count = 0; setInterval(() => { this.count += 1; // Arrow function does not have its own 'this' console.log(this.count); }, 1000); } const counter = new Counter();
In this example:
以上是掌握 JavaScript 函數:開發人員綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!