2017/5 JavaScript Foundation 8 - Functions, Scopes

I. Overview of Functions

1. Concept

A function is a block of JavaScript code that is defined once but can be executed and invoked many times. Functions are also objects. They can operate and transfer functions like other objects. Functions in Js are also called function objects.

2. Return value

1. The return value of a normal function depends on the return statement. If there is no return statement, undefined is returned by default.

2. As a constructor, a new call is used externally. If there is no return statement, or if the return is a basic type, this will be returned. If an object is returned, it will be regarded as the return value of the new constructor.

3. Different ways of calling

  1. Direct call: foo();
  2. Method calls as objects: o.method();
  3. Constructor: new Foo();
  4. call/apply/bind : func.call(o);

Statements and expressions

1. Function declaration

Beginning with function, without parentheses, not assigned to other variables

function add(a,b){
  a = +a ;
  b = +b ;
  if(isNaN(a)||isNaN(b){
     return;
  }) 
  return a+b
}

2. Functional expression

//Anonymous function assignment
var add = function(a,b){
  //do sth
}

//Put anonymous functions in parentheses -- function expressions -- and execute them immediately.
(function(){
   //do sth
})();

//Function object as return value, function expression
return function(){
  //do sth
};

//
var add = function foo(a,b){
  //do sth
};

//Real-Named Function Assignment--Named Function Expressions
var add = function foo (a,b){
  //do sth
}

3. Pre-declaration of Variable-Function

The main difference between function expressions and function declarations is that function declarations are prefixed.

Function expressions must be declared before they are called.

//Function declaration
var num = add(1,2);
console.log(num); //3 Function declaration can be invoked successfully

function add(a,b){
  a = +a;
  b = +b;
  if(isNaN(a)||isNaN(b)){
    return ;
  }
  return a+b;
}

//Functional expression -- variable add is undefined with an advance value
var num = add(1,2);  //undefined is not a function
console.log(num);

var add = function(a,b){  //Anonymous function expression, assigned to add
  a = +a;
  b = +b;
  if(isNaN(a) || isNaN(b)){
    return;
  }
  return a+b;
}

4. Named Function Expressions (NFE)

Functional expressions with names (not often used)

var func = function nfe(){};

//Recursive call
var func = function nfe(){
  /***do sth**/
 nfe()
};

5. Function constructor

//1. Parametric 2. Code
var func = new Function('a','b','console.log(a+b);');
func (1,2);//3

//No new effect
var func = Function('a','b','console.log(a+b);');
func (1,2);//3

var func = Function('a','b','console.log(a+b);')(); //Immediate call

III. this Pointer

1. This (Browser) in Global Scope

The global scope this points to the global object. In the browser, the global object is window. This.a is equivalent to window.a.

1) Variable declaration

console.log(this.document === document); //true
console.log(this === window); //ture this and window are equal

this.a = 37;  //Create a global variable a
console.log(window.a) ; //37

2) Function declaration

function f1(){
  return this;
}

f1() === window ; // true browser this refers to window, Nodejs this refers to global


function f2(){
  "use strict"; //see thrict mode "strict mode"
  return this ;  //this points to undefined
}

f2() === undefined; //true

2. this as a function of the object method

When a function is called as an object method, this in the function points to the object that calls it.

var o = {          // Create object independent variable o
  prop:37,
  f:function(){    //Creating Object Method
    return this.prop;
  }
};

console.log(o.f()); //logs 37 o.f() calls this to point to o


var o = { prop :37};  //Create object arguments

function independent(){
  return this.prop
}
//Call independent this directly to point to window in the browser

o.f = independent; //Create object attribute f to point to function object

console.log(o.f()); //logs 37 // / this points to the object when invoked

3. this on the Object Prototype Chain

var o = {
  f: function(){     // Object Method
    return this.a + this.b;
  }
}

var p = Object.create(o);  //Create an empty object p prototype pointing to o

p.a = 1; //Create attributes on objects
p.b = 4;

console.log(p.f()); //5 Call the method this on the prototype chain to point to p

4. get/set method and this

function modulus(){
  return Math.sqrt(this.re*this.re + this.im*this.im);
}

var o = {
  re:1,
  im:-1,
  get phase(){  
   return Marh.atan2(this.im , this.re)
  }
}

//Adding attributes to objects

Object.defineProperty(o,"modulus",{
  get:modulus,enumerable:true,configurable:true
});

cosole.log(o.phase, o.modulus); //- 0.78 1.4142 this all point to o

5) this in the constructor

function MyClass(){
  this.a = 37 ; //Normally call this to point to the global object window
}

var o = new myClass(); //When a function is called as a constructor,
//Here this points to an empty object o, and the prototype of O points to MyClass.prototype

console.log(o.a); //37 returns this to get this by default when there is no return value

function C2() {
  this.a = 37;
  return {a:38}; //Returns an object that is returned as a return value
}

o = new C2(); // O is not this, o is the returned object
console.log(o.a); //38

6) call/apply method and this

function add(c,d){
  return this.a + this.b + c +d;
}

var o = {a:1,b:3};
// The first parameter is the this object that you want to add, followed by the imported parameter.
add.call(o,5,7); //1+3+5+7 =16

//The difference with apply is that the parameters passed in are arrays

add.apply(o,[10,20]); //1+3+10+20= 34


function bar(){
  console.log(Object.prototype.toString.call(this));
}

bar.call(7); //"[object Number]"

7)bind method and this

//IE9+
function f(){
  return this.a
}
//Taking an object as this, 
var g = f.bind({a:'test'}); f in this point bind Object in
console.log(g()) ; //test 

//The method o f assigning F and g as objects to object o 
var o = {a:37, f:f, g:g};
console.log(o.f, o.g); //37 ,test

Functional attributes: argument

1. Relevant parameters

  1. foo.name -- function name
  2. foo.length -- Number of formal parameters
  3. argument.length -- Number of arguments

aegument is an object of an array of classes. There are no join slice or other array methods, but it can be read by index.

function foo(x,y,z){
  arguments.length; //2 -- Get the incoming real parameters
  arguments[0]; //1

/******Binding Relations****/
  arguments[0] = 10;
  x; //The argument becomes 10
/*******************/

/***There is no binding relationship***/
  arguments[2] = 100;
  z; //still undefined does not pass in parameters, and there is no binding relationship between argument and parameters
/******************/

  arguments.callee === foo; //true
}
//There is no binding relationship in the strict "use strict" mode, arguments.callee cannot be used

foo(1,2); // Two parameters are actually passed in
foo.length; //3 has three parameters x, y and z
foo.name; //"foo" returns the function name·

2. Application/call method (browser)

function foo(x,y){
  console.log(x,y,this);
}

//The first parameter is the this object that you want to pass in, not the object that will be converted to the corresponding wrapper class.
foo.call(100,1,2); //Number value (100)
foo.apply(ture,[3,4]); //3,4,Boolean(true) afferent array
foo.apply(null); //undefined,undefined, window --this points to the global object
foo.apply(undefined); //undefined,undefined, window --this points to the global object

//Strict mode
function foo(x,y){
  " use strict"
  console.log(x,y,this);
}

foo.apply(null); //undefined,undefined, null
foo.apply(undefined); //undefined,undefined,undefined

3. bind method

1) Change the direction of this function


this.x = 9; //window.x Global Variable x
var module = { //Object Argument
  x:81,
  getX:function(){ return this.x;}
};

module.getX(); //81   

var getX = module.getX; //Assigning methods to variables
getX(); //9 this points to global variables

//bind changes the this pointing of the function at run time
var boundGetX = getX.bind(module); //When boundGetX runs, this points to module
boundGetX();81

2) Function granulation: bind currying

function add(a,b,c){
  return a+b+c; //Return value
}

//No need to change this, pass undefined, and pass in the first parameter 100
var func = add.bind(undefined,100); //a binding 100
func(1,2); //103  b =1 ; c =2;

var func2 = func.bind(undefined,200);  // b Binding 200
func2(10); //310  

3) Examples

function getConfig( colors,size,otherOptions){ //Get configuration
  console.log(colors,size,otherOptions);
}

var defaultConfig = getconfig.bind(null,"#CC0000","1024*768"; // Import Common Configuration

defaultConfig("123"); //#CC0000","1024*768 123
defaultConfig("456"); //#CC0000","1024*768 456

3)bind and new

functn foo(){
  this.b = 100;
  return this.a;
}

//The foo this pointer points to the object passed in by bind
var func = foo.bind({a:1});

func(); //1 this points to the bind parameter

// Using new, if the return is not an object, return this,this is initialized as an empty object, and the object's prototype is foo.prototype.
new func(); //Returns {b:100} object argument, ignoring bind

4) bind method simulation

from: Mu Course Network

Keywords: Javascript Attribute network

Added by kodlcan on Sun, 30 Jun 2019 04:55:44 +0300