Home Web Front-end JS Tutorial JavaScript function calling and parameter passing_Basic knowledge

JavaScript function calling and parameter passing_Basic knowledge

May 16, 2016 pm 03:35 PM
javascript function

JavaScript function call
There are 4 ways to call JavaScript functions.
The way each differs is in the initialization of this.
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.
Call JavaScript function
The code within the function is executed after the function is called.
Call as a function
Example

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


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

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


Note This is a common way to call JavaScript functions, but it is not a good programming practice
Global variables, methods or functions can easily cause naming conflict bugs.
Global Object
When 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:
Example

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


Note: Calling a function as a global object will make the value of this a global object.
Using the window object as a variable can easily cause the program to crash.
Function called as method
In JavaScript you can define functions as methods of objects.
The following example creates an object (myObject) with two properties (firstName and lastName), and one method (fullName):
Example

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


The fullName 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 below! Modify the fullName method and return this value:
Example

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


Note: When a function is called as an object method, the value of this becomes the object itself.
Use constructor to call 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 recreated objects:
Example

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

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

Copy after login


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.
Call function as function method
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.
Example

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

Example

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


Both methods use the object itself as the first parameter. 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, the first parameter becomes the value of this when calling a function, even if the parameter is not an object.
In JavaScript non-strict mode, if the value of the first parameter is null or undefined, it will use the global object instead.
Note With the call() or apply() methods you can set the value of this and call it as a new method on an existing object.

JavaScript function parameters
JavaScript functions do not perform any checks on parameter values ​​(arguments).
Function explicit parameters and hidden parameters (arguments)
In previous tutorials, we have learned about explicit parameters of functions:

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


函数显式参数在函数定义时列出。
函数隐藏参数(arguments)在函数调用时传递给函数真正的值。
参数规则
JavaScript 函数定义时参数没有指定数据类型。
JavaScript 函数对隐藏参数(arguments)没有进行检测。
JavaScript 函数对隐藏参数(arguments)的个数没有进行检测。
默认参数
如果函数在调用时缺少参数,参数会默认设置为: undefined
有时这是可以接受的,但是建议最好为参数设置一个默认值:
实例

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

或者,更简单的方式:
实例

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

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;
}

Copy after login

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

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;
}

Copy after login


通过值传递参数
在函数中调用的参数是函数的参数。
如果函数修改参数的值,将不会修改参数的初始值(在函数外定义)。
函数参数的改变不会影响函数外部的变量(局部变量)。
通过对象传递参数
在JavaScript中,可以引用对象的值。
因此我们在函数内部修改对象的属性就会修改其初始的值。
修改对象属性可作用于函数外部(全局变量)。

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks 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.

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 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.

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.

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.

See all articles