JavaScript Function (1) - Definition and Call of Function

JavaScript Function (1) - Definition and Call of Function

Label (Space Separation): JavaScript

order

A function is a piece of JavaScript code that is defined only once, but may be executed or called any time.

JavaScript functions are parameterized: the definition of a function includes a list of identifiers called formal parameters that work like local variables in the body of the function.
In JavaScript, functions are objects.

Definition of function

function fn(){};

Defining Functions with Function Statements

// Output the name and value of each attribute of o, returning undefined
function printprops(o){
    for(var p in o){
        console.log(p + ":" + o[p] + "\n");
    }
}

// Calculate the distance between two Cartesian coordinates (x1,y1) and (x2,y2)
function distance(x1,y1,x2,y2){
    var dx = x2 - x1;
    var dy = y2 - y1;
    return Math.sqrt(dx*dx + dy*dy);
}

// Recursive function for calculating factorial
function factorial(x){
    if(x<=1) return 1;
    return x*factorial(x-1);
}

Define functions with expressions

// Assign a function to a variable
var square = function(x){ return x*x; };

// Functional expressions can contain names, which are useful in recursion
var f = function fact(x){
    if (x<=1) return 1;
    else return x*fact(x-1);
}

// Functional expressions can also be passed as parameters to other functions.
data.sort(function(a,b){ return a-b; });

//Functional expressions are sometimes called immediately after they are defined
var tensquared = (function(x){ return x*x; }(10));

Function declaration statements (the first) are "advanced" to the top of an external script or scope of an external function, so functions declared in this way can be called by code that appears before it is defined.
Functions defined by expressions (the second kind) must be assigned to a variable first. The declaration of variables will be advanced, but the assignment of variables will not be advanced. Therefore, functions defined by expressions cannot be invoked before definition.

The return statement causes the function to run customized and returns the value of the return expression (if any) to the caller. If the return statement does not have an expression associated with it (or the function does not contain the return statement), it returns undefined to the caller.

Functions can nest functions, such as:

function hypotenuse(a, b){
    function square(x){
        return x*x;
    }
    return Math.sqrt( square(a) + square(b) );
}

Function declarations are not real statements (the ES specification only allows them to be top-level statements)
Functions (restricted to functions defined in statement declaration form) cannot appear in loops, conditional judgements, or try/cache/finally/with statements (FF allows conditional function declarations in if statements)

function call

JavaScript code that forms the body of a function is not executed when defined, but only when functions are called.

There are four ways to call functions:

  • As a function
  • As a method
  • As a constructor
  • Indirect calls through their call() and apply() methods

function call

Ordinary function calls or method calls can be made using call expressions.

printprops({x:1});
var total = distance(0, 0, 2, 1, ) + distance(2, 1, 3, 5);
var probability = factorial(5)/factorial(13);

According to ES3 and non-strict ES5 rules on function calls, the call context (this) is a global object, while in ES5 strict mode, the call context is undefined.

Functions called in the form of functions usually do not use this keyword, but this can be used to determine whether the current pattern is strict.

// Define and call a function to determine whether the current script runs in strict mode
var strict = (function(){ return !this; }());

Method calls

A method can be thought of as a JavaScript function stored in an object property.

 // If you have a function f and an object o, you can define a method called m() for o with the following code
 o.m = f;
 // Call the m() method
 o.m();
 // If m() requires two arguments
 o.m(x, y);

There is an important difference between method calls and function calls, that is, the calling context:
The attribute access expression consists of an object and an attribute name. In the method call expression of the preceding example, the object o is the calling context, and the function body can refer to the object by using the keyword this.

var calculator = {
    operand1: 1,
    operand2: 2,
    add: function(){
        this.result = this.operand1 + this.operand2;
        return this.result;
    }
};
console.log(calculator.operand1); // => 1
console.log(calculator.add()); // => 3
console.log(calculator.result); // => 3

View the results on JS Bin

Use [] for attribute access operations

o["m"](x, y);

Method calls may include more complex attribute access expressions

// Call customer.surnameMethod
customer.surname.toUpperCase();
// Continue to call the m() method in the return value after the f() call ends
f().m();

Method and this keyword are the core of object-oriented programming paradigm
Any function that acts as a method call actually passes in an implicit argument -- an object whose parent is the method call.

// In contrast, the first line of code-method invocation syntax makes it very clear that the carrier of this function's execution is the rect object.
rect.setSize(width, height);
setSize(rect, width, height);

This is a keyword, not a variable, nor an attribute name. JavaScript syntax does not allow this to be assigned.
Unlike variables, this has no scope restrictions, and nested functions do not inherit this from functions that call it. If a nested function is called as a method, its this value points to the object being called; if a nested function is called as a function, its this value is either a global object (non-strict mode) or undefined (strict mode).

If you want to access the value of this external function, you need to save the value of this in a variable, which is in the same scope as the internal function.

var o = {
  m: function(){
    var self = this;
    console.log(this === o);
    f(); // Nested functions are called as functions

    function f(){
      console.log(this === o); // => false
      console.log(this); // => Global object orundefined
      console.log(self === o); // => true
    }

  }
};

o.m();

View the results on JS Bin

constructor call

If a function or method call is preceded by a keyword new, it constitutes a constructor call.

// The following two codes are equivalent
var o = new Object();
var o = new Object;

The constructor call creates a new object that inherits the prototype attribute of the constructor. The constructor attempts to initialize the new object and use it as its calling context, so the constructor can use this keyword to reference the newly created object.
Although the constructor looks like a method call, it still uses the new object as the call context, that is, in the expression new o.m(), the call context is not o.
Constructors usually do not use return keywords

Indirect call

call() and apply() methods can be used to call functions indirectly, both of which allow the display of this value required for the call.

From the JavaScript Authoritative Guide, not to be continued.

A coder on the way swpuLeo

Keywords: Javascript Attribute calculator Programming

Added by skeppens on Wed, 03 Jul 2019 02:24:08 +0300