Javascript methods for calling functions are: 1. Use the constructor to call the function, the code is [function myFunction(arg1, arg2)]; 2. Call the function as a function method.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Javascript methods for calling functions are:
1. Use the constructor to call the function
If new is used before the function call keyword, the constructor is called.
This looks like a new function is created, but in fact JavaScript functions are recreated objects:
Instance
// 构造函数: 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 function is called to instantiate the object (new object).
2. Call the function as a 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; } myObject = myFunction.call(myObject, 10, 2); // 返回 20
Example
function myFunction(a, b) { return a * b; } myArray = [10, 2]; myObject = myFunction.apply(myObject, myArray); // 返回 20
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 (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.
Related free learning recommendations: javascript video tutorial
The above is the detailed content of What are the methods for calling functions in javascript?. For more information, please follow other related articles on the PHP Chinese website!