Home Web Front-end Front-end Q&A What are the ways to write javascript functions?

What are the ways to write javascript functions?

Apr 12, 2021 pm 02:27 PM
javascript function

How to write function: 1. "function function name(){}"; 2. "var function name = function(){}"; 3. "(function(){...})()" ;4. "(function(){...}())"; 5. "$(function(){})".

What are the ways to write javascript functions?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript is more casual than other programming languages, so Javascript code is full of all kinds of weird ways of writing, and sometimes it’s just a blur. This article talks about how to write JavaScript functions.

In Javascript there are only objects. Variables are objects, and functions are also objects. As long as you know what your object is, just use it the way it is used.

Javascript is weakly typed, objects, instances, functions, and methods are universal. The distinction does not need to be so clear.

1. Conventional writing:

// 函数的定义
function foo() {
    alert('常规写法');
}
// 函数的调用
foo()
Copy after login

This writing method is the most familiar and easiest to understand writing and calling method. Then read on

2. How to write anonymous functions

// 函数的定义
var foo = function(){
    alert('匿名函数定义');
}
// 函数的调用
foo()
Copy after login

The function definition is made anonymous, eliminating the pain of naming. At the same time, it is assigned to a variable, and the variable becomes a synonym for the function. Next, see

3. Using the method as an object

// 定义
var test = {
    fun1: function(){  },
    fun2: function(){  }
}
// 调用
test.fun1();
test.fun2();
Copy after login

in Variables in Javascript are very powerful and can represent many things.

4. Add methods to the object in the constructor

// 给对象添加方法
var fun = function(){ };  // 定义函数对象
fun.prototype.test = function(){ 
    alert('这是在在foo函数上的原始对象上添加test方法,构造函数中用到');
}

// 调用
var myfun = new fun(); // 创建对象
myfun.test(); // 调用对象属性
Copy after login

Add methods through the prototype keyword.

5. Self-executing functions ( function(){…} )() and ( function(){…} () )

The function definition and call mentioned earlier are separated, but the definition and execution discussed immediately here are done together.

( function(){…} )() and ( function(){…} () ) are two common ways of writing JavaScript functions to execute immediately. At first, I thought it was an anonymous function wrapped in parentheses, and then Adding parentheses at the end to call the function finally achieves the purpose of executing the function immediately after it is defined. Later, it was discovered that the reason for adding parentheses was not the same. To understand the immediate execution of functions, you need to first understand some basic concepts of functions.

Function declaration, function expression, anonymous function

Function declaration: function fnName () {…}; Use the function keyword to declare one function, and then specify a function name, called Function declaration.

Function expression var fnName = function () {…};Use the function keyword to declare a function, but do not give the function a name. Finally, assign the anonymous function to a variable, called Function expression, this is the most common syntax form of function expression.

Anonymous function: function () {}; Use the function keyword to declare a function, but do not give the function a name, so it is called an anonymous function. Anonymous functions belong to function expressions. Anonymous functions have There are many functions, assigning a variable creates a function, assigning an event becomes an event handler or creates a closure, etc.

The difference between function declaration and function expression is that

1. The Javascript engine will 'Function declaration Hoisting' the current execution environment (scope) when parsing the JavaScript code. function declaration on, and the function expression must wait until the Javascirtp engine executes to the line where it is located, then the function expression will be parsed line by line from top to bottom.

2. You can add parentheses after the function expression immediately To call this function, function declaration is not allowed and can only be called in the form of fnName(). Here are two examples of the difference.

// 方式1: ( function(){…} () )
(
     function(){alert('hello world, I am coming');}()
);
// 函数有参数的情况,有时为确保执行,前面加;
// 看到别人的插件,你会发现人家开头处加了一个";",这样就算页面js有错误,加载运行他的插件也能保证运行,如:
;(function(e){alert(e);}('hello world'));

// 方式2:( function(){…} )()
(function(){alert('hello');})();

// 有时在前面加运算符,常见的是!与void
!function(){alert('hello');}();
void function(){alert(2);}();
Copy after login

6 $(function(){})Writing

$ (function(){/<em>…</em>/}); is the abbreviation of $(document).ready(function(){/<em>…</em>/}), which is executed after the DOM is loaded. The callback function will only be executed once.

$( document ).ready(function() {
   console.log( "ready!" );
});
Copy after login

is equivalent to the following writing

$(function() {
   console.log( "ready!" );
});
Copy after login

Written in different js on one page$(function(){/<em>…</em>/}); Function will be executed sequentially according to the order of js.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What are the ways to write javascript functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles