Javascript: understanding functions

Time:2021-4-21

Understanding functions

Most of the words are written. Don’t be bored~~

  • In JavaScript, every function is actually a function object. (isn’t there a saying that everything is the object? )

  • Functions always return a value, but a procedure may or may not return a value. (so a function is not a procedure ~)

    • If a return statement is not used in a function, it returns undefined by default. To return a specific value, the function must use the return statement to specify a value to return. (except for calling a constructor with the new keyword).

  • When a function is called, the value passed to the function is called the actual parameter of the function (value passing), and the function parameter at the corresponding position is called the formal parameter.

    • If the argument is a variable containing the original value (number, string, Boolean value), the value of the argument will not change even if the function changes the value of the corresponding parameter internally.

    • If the argument is an object reference, the corresponding shape reference and the argument point to the same object. If the function changes the value of the corresponding parameter internally, the value of the object that the parameter points to will also change after returning.

Finally, there’s a code. Sprinkle flowers ~~

/*Define the function myfunc*/
 function myFunc(theObject)
 {
   //The argument mycar and the formal parameter theobject point to the same object
   theObject.brand = "Toyota";
 }
 
 /*
  *The variable mycar is defined;
  *  Create and initialize an object ;
  *Assign the reference of the object to the variable mycar
  */
 var mycar = {
   brand: "Honda",
   model: "Accord",
   year: 1998
 };

 /*Pop up 'Honda'*/
 window.alert(mycar.brand);

 /*Passing object references to functions*/
 myFunc(mycar);

 /*
  *Pop up 'Toyota', the property of the object has been modified
  */
 console.log(mycar.brand);

(about this in function, by the way)

When a function is executed, this keyword does not point to the running function itself, but to the object calling the function.
Therefore, if you want to get the reference of the function itself inside the function, you can only use the function name or the arguments.callee attribute
If the function is anonymous, you can only use the latter.