Home >Web Front-end >JS Tutorial >How to define a method in javascript

How to define a method in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-09 11:16:113734browse

How to define a method: 1. Definition formula, define the method first and then call it, the syntax is "function function name (parameter) {code to be executed}"; 2. Variable formula, the syntax is "var variable name=function Function name (parameters) {code to be executed}".

How to define a method in javascript

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

Functions in JavaScript are similar to methods in Java. They are statement blocks that perform specific functions. There are two ways to define functions:

The difference between the two ways of defining functions: the first is called definition, and the second is called variable. In practical applications, there is no difference between the two, but there is a difference in the order of calls: definitions can be defined after calls, but variable expressions cannot. The example is as follows
1, definition formula

<script>
function test(age){		//先定义方法,再调用
	console.log(age);
}
test(23);
</script>

<script>
test(23);	
function test(age){		//先调用,再定义方法,不会出错
	console.log(age);
}
</script>

2, variable formula

<script>
	var print=function(name){
		console.log(name);
	}
	print("tom");
</script>

<script>
		print("tom");		//先调用,再定义会出错。
		var print=function(name){
			console.log(name);
		}
</script>

Function parameter list and return value:

Function parameter list: Parameters in the function parameter list in JavaScript are not allowed to have data types; the number of function parameters It can be 0~255. When there are multiple parameters, separate them with commas;

Function return value: The JavaScript function does not define the return value type part of the function. The JavaScript function returns the value according to the return value in the function body. statement to determine the return value type; if there is no return return value statement, the function has no return value.

Note:

When declaring a variable inside a function, if the var keyword is ignored, the variable will be a global variable, as shown in the following example:

The twelfth line of code will go wrong after defining var

[Recommended study:javascript advanced tutorial

The above is the detailed content of How to define a method in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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