Explain the usage of this keyword in JavaScript basic knowledge

Source: Internet
Author: User

This is a special object within the function that refers to the environment object in which the function is executed (as we will add in the end of the article), the value of this is not determined before the call function, and different invocation methods cause this value to change.

Window.num =;
var o = {num:11};
function Saynum () {
  alert (this.num)
}
saynum ();//22
o.saynum = saynum;
O.saynum ();//11

Remember: The function name is just a variable that contains a pointer. So even if executed in different environments, the global Saynum () function is still pointing to the same function as O.saynum ().

1. When calling a function in a global scope
called in global scope, this object refers to window
The execution of an anonymous function is global, so its this object usually points to window

function fn1 () {
  console.log (this);
}

FN1 ();

2. Call via new operator
This is a reference to an instance object

function person (name) {
  this.name = name;
}
Person.prototype.printName = function () {
  alert (this.name);//byron
};

var p1 = new Person (' Byron ');

3. Method calls as objects
this refers to the object

var obj1 = {
  name: ' Byron ',
  fn:function () {
    console.log (this);
  }
;

Obj1.fn ();

4. Indirect call
Call and apply
Each function contains two methods that are not inherited: Call () and apply (). The purpose of both methods is to call a function in a particular scope, which is actually equal to the value of the This object in the function body. That is, calling the function directly, specifying the execution environment when called

Window.color = ' red ';
var o = {color: ' Blue '};
function Saycolor () {
  alert (this.color);
}
Saycolor.call (this);//red
saycolor.call (window);//red
Saycolor.call (o);//blue

(1) Apply method
receives two parameters, one is the scope of the function in the function, and the other is the parameter array.

(2) Call method
The call method is the same as the Apply method, except that the parameters are received in a different way, and the first parameter is the this value unchanged for the call method, and the change is that the rest of the parameters are passed directly to the function.

function fn () {
   Console.log (this)//windwow
   function Innerfn () {
     console.log ()
   }
   Innerfn.call (This)//window
}
fn ();
 function Fn0 () {
   Console.log (this)//window
}
function fn1 () {
   fn0.call (this);
   Console.log (this);//window
}
fn1 ();
function Fn0 () {
 Console.log (this)//object
}
var o = {
  fn1:function fn1 () {
    fn0.call (this);
    Console.log (this);//object
  }
}
o.fn1 ();  

5.bind method
This method creates an instance of the function whose this value is bound to the value passed to the bind () function. That is, a new function is returned, and the this within the function is the first argument passed in

Window.color = ' red ';
var o = {color: ' Blue '};
function Saycolor () {
  alert (this.color)
}
var objectsaycolor = Saycolor.bind (o);
Objectsaycolor ();//blue

Supplemental NOTES: Implementing Environmental definitions
Other data that defines a variable or function has access to it, and each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in this object. The code we write does not have access to this object, but the parser uses it in the background while processing the data.
the creation of an execution environment:

1. Global implementation Environment
in a Web browser, the global execution environment is considered a Window object, so all global variables and functions are created as properties and methods of the Window object. When the code is loaded into the browser, the global execution environment is created (the global execution environment is destroyed when we close the Web page or the browser).

2. Local execution Environment
each function has its own execution environment, so the local execution environment is a function object. When the function is invoked the local environment of the function is created (after the execution of the code within the function, the environment is destroyed, and all the variables and function definitions stored therein are destroyed).

The execution environment and the associated variable object are abstract concepts that are explained as follows

var a = 1;
function fn (num1,num2) {
  var b = 2;
  function Fninner () {
    var c = 3;
    Alert (A + B + c);
  }
  Fninner (); Local execution Environment creation
}
fn (4,5) at//fninner call; local execution environment created when called//FN

Ii. Scope Chain
the execution of a JavaScript function uses the scope chain, which is created when the function is defined, and when a function is defined, it actually saves a scope chain. When this function is called, it creates a new object to store its local variables and adds the object to the saved scope chain. The front end of the scope chain is always the variable object of the environment in which the currently executing code resides. The end of the scope chain is always the variable object of the global execution environment. The purpose of the scope chain is to guarantee access to all variables and functions that are granted access to the execution environment

var scope = ' global scope ';
function Checkscope () {
  var scope = ' local scope ';
  function f () {return scope};
  return f;
}
Checkscope () ();//local scope

Understanding: When calling Checkscope, function f is defined and bound to the Checkscope scope chain as a local variable, so the function f is still valid wherever it is invoked, so the return value is global scope.

var num1 = 1;
function Outer () {
  var num2 = 2;
  Console.log (NUM1 + num2);//3
  function Inner () {
    //Here you can access Num3,num2,num1
    var num3 = 3;
    Console.log (num1 + num2 + num3)//6
    }
  //Here can access Num2,inner (), NUM1 but cannot access num3 Inner
  ();
}
Outer ();
Console.log (NUM1);//1, execution Environment
//only access to NUM1 here

Scope chain (search up): The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment.

 var name = ' Byron ';
  function fn () {
    var name = ' Csper ';
    Console.log (name);//casper
  }
  fn ();


The more the internal environment, the higher the weight of the variable.

Note: A variable without a direct declaration with the Var keyword belongs to a global variable such as declaring a = 1 directly, at which point A is a global variable.

When the Javscript engine enters the scope, it handles the code in two rounds. First round, initialize variables. Second round, executing code

var a = 1;
Function Prison (a) {
  console.log (a);//1
  var A;
  Console.log (a);//1
}
Prison (1);

Third, function execution
when a function call enters the execution environment, it first processes the arguments, the initial Huafing parameter (the default is undefined), and then initializes the function declaration within the function, and then initializes the variable declaration within the function when the code is executed step-by-step (entering the environment when execution code is not started). value is undefined). So the initialization order within the function is the formal parameter, the function declaration, and the variable declaration. As you can see from the picture above. Let me give you an example (the entire global environment is also a function).

Alert (typeof fn);//function, function declaration advance
alert (typeof fn0);//undefined, variable declaration in advance but not assigned
function fn () {
//function expression
}
var fn0 = function () {
//function-defined
}
alert (typeof fn0);//function, the variable is already assigned

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.