search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript function calling and parameter passing usage examples

JavaScript function call

The difference between each method lies in the initialization of this.

Pass parameters by value
The parameters called in the function are the parameters of the function. If a function modifies the value of a parameter, it will not modify the parameter's initial value (defined outside the function). Changes to function parameters will not affect variables outside the function (local variables).
Passing parameters through objects
In JavaScript, you can reference the value of an object. Therefore, when we modify the properties of the object inside the function, its initial value will be modified. Modifying object properties can act outside the function (global variables).

this Keyword

Generally speaking, in Javascript, this points to the current object when the function is executed. Note Note that this is a reserved keyword, you cannot modify the value of this.

Calling JavaScript functions

The code in the function is executed after the function is called.

Called as a function

Instance


##

function myFunction(a, b) {
  return a * b;
}
myFunction(10, 2);      // myFunction(10, 2) 返回 20

The above function does not belong to any object. But in JavaScript it is always the default global object. The default global object in HTML is the HTML page itself, so the function belongs to the HTML page. The page object in the browser is the browser window (window object). The above functions will automatically become functions of the window object. myFunction() and window.myFunction() are the same:



function myFunction(a, b) {
  return a * b;
}
window.myFunction(10, 2);  // window.myFunction(10, 2) 返回 20

Note This is a common method for calling JavaScript functions, but it is not a good programming habit. Or functions can easily cause bugs in naming conflicts.


Global objectWhen the function is not called by its own object, the value of this will become the global object. In a web browser the global object is the browser window (window object). The value of this returned by this instance is the window object:


function myFunction() {
  return this;
}
myFunction();        // 返回 window 对象

Note If the function is called as a global object, the value of this will become the global object. Using the window object as a variable can easily cause the program to crash.

Function calls as methods

In JavaScript you can define functions as methods of objects. The following example creates an object (myObject), which has two properties (firstName and lastName), and one method (fullName):



var myObject = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}
myObject.fullName();     // 返回 "John Doe"

fullName The method is a function. Functions belong to objects. myObject is the owner of the function.

This object holds JavaScript code. The value of this in the instance is the myObject object. Test the following! Modify the fullName method and return this value:


var myObject = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this;
  }
}
myObject.fullName();     // 返回 [object Object] (所有者对象)

Note When the function is called as an object method, the value of this will become the object itself.

Use the constructor to call the function

If the new keyword is used before the function call, the constructor is called.

This looks like a new function is created, but in fact JavaScript functions are re-created objects:


// 构造函数:
function myFunction(arg1, arg2) {
  this.firstName = arg1;
  this.lastName = arg2;
}

// This creates a new object
var x = new myFunction("John","Doe");
x.firstName;               // 返回 "John"

The call to the constructor creates a new object. The new object inherits the constructor's properties and methods. Note The this keyword in the constructor does not have any value. The value of this is created when the object (new object) is instantiated when the function is called.

Calling functions as function methods

In JavaScript, functions are objects. A JavaScript function has its properties and methods.

call() and apply() are predefined function methods. Two methods can be used to call functions, and the first parameter of both methods must be the object itself.


function myFunction(a, b) {
  return a * b;
}
myFunction.call(myObject, 10, 2);   // 返回 20

Instance



function myFunction(a, b) {
  return a * b;
}
myArray = [10,2];
myFunction.apply(myObject, myArray);  // 返回 20

Both methods use the object itself as the first parameters. The difference between the two lies in the second parameter: apply passes in a parameter array, that is, multiple parameters are combined into an array and passed in, while call is passed in as the parameter of call (starting from the second parameter).

In JavaScript strict mode (strict mode), the first parameter will become the value of this when calling the function, even if the parameter is not an object.
In JavaScript non-strict mode (non-strict mode), if the value of the first parameter is null or undefined, it will use the global object instead.
Note Through the call() or apply() method you can set the value of this and call it as a new method of an existing object.

JavaScript function parameters

JavaScript functions do not perform any checks on the values ​​of parameters (arguments).

Function explicit parameters and hidden parameters (arguments)In the previous tutorial, we have learned about the explicit parameters of the function:


functionName(parameter1, parameter2, parameter3) {
  code to be executed
}

Explicit parameters of functions are listed when the function is defined.

Function hidden parameters (arguments) are the real values ​​passed to the function when the function is called.

参数规则
JavaScript 函数定义时参数没有指定数据类型。
JavaScript 函数对隐藏参数(arguments)没有进行检测。
JavaScript 函数对隐藏参数(arguments)的个数没有进行检测。
默认参数
如果函数在调用时缺少参数,参数会默认设置为: undefined

有时这是可以接受的,但是建议最好为参数设置一个默认值:


function myFunction(x, y) {
  if (y === undefined) {
     y = 0;
  } 
}

或者,更简单的方式:


function myFunction(x, y) {
  y = y || 0;
}

Note 如果y已经定义 , y || 返回 y, 因为 y 是 true, 否则返回 0, 因为 undefined 为 false。如果函数调用时设置了过多的参数,参数将无法被引用,因为无法找到对应的参数名。 只能使用 arguments 对象来调用。

Arguments 对象
JavaScript 函数有个内置的对象 arguments 对象.argument 对象包含了函数调用的参数数组。通过这种方式你可以很方便的找到最后一个参数的值:


x = findMax(1, 123, 500, 115, 44, 88);

function findMax() {
  var i, max = 0;
  for (i = 0; i < arguments.length; i++) {
    if (arguments[i] > max) {
      max = arguments[i];
    }
  }
  return max;
}

或者创建一个函数用来统计所有数值的和:


x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
  var i, sum = 0;
  for (i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
}

The above is the detailed content of Detailed explanation of JavaScript function calling and parameter passing usage examples. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment