Master JS in the "This" (a)

Source: Internet
Author: User
Tags babeljs

Translator Note: in general, function translation is a function, method translated into a method.

We generally say that the method of such an object does not say "the function of a certain object". The reason is that in object-oriented, an object is an instance of a specific amount, with its own method. And the function is not the same as the object.

In addition, scope (scope) and context (context) is also a confusing place. Please refer to: Javascript context and some learning summaries of scope

Recommended reading: ES6 (1~10) series

Writing a program in a language does not mean that the language can be properly understood and used. Of course, so is JavaScript. Although JS(JavaScript abbreviation) is a very easy to learn the language, but there are actually many details, beginners may not understand, even the experienced JS ace will occasionally fall into the pit.

Many experienced programmers are this also confused about how to operate inside JS. Popular point, this just a reference alias (referencing alias)-This alias only knows the current point of the object, and this is the most difficult place.

This article is for you to clear up the idea, and introduce this the internal operation of the key word principle.

So thisWhat kind of a ghost?

In short, this it is a special identifier keyword--automatically determined by scope (scope) in each function, pointing to the " owner" of the call. But to get this whole thing done, we need to answer two key questions:

thisHow was it created?

Each time a JavaScript function is called, a new object is created, including: Which arguments are passed in, how the function is called (invoked), where the function is called (called), and so on. Another important property in the object is a this reference to the object's method, which is this automatically bound to the object.

tip: for details, refer to the ECMAScript Language Specification §10.4.3 section and RELATED links.

var car = {  brand: "Nissan",  getBrand: function(){    console.log(this.brand);  }};car.getBrand();// output: Nissan

In this example, the use is this.brand that this is a car reference to the object. So at this point, it is this.brand equivalent to car.brand .

thisWho is it pointing to?

In all this functions, the value is determined by the context inwhich the function is located at the time of the call. Scope this (scope) is not related to the location defined by the function, but depends on where the function is called (where they is called from; i.e. the context).

Each line of JavaScript code is run in the execution context (execution context). The this object pointed to is fixed each time it enters a new execution context until the jump (shifted) changes to a different context. The decision execution context (and this the binding) requires us to find the call point (call-site) where the function is called in the code.

Let's look at the following example:

var brand = ‘Nissan‘;var myCar = {brand: ‘Honda‘};var getBrand = function() {  console.log(this.brand);};myCar.getBrand = getBrand;myCar.getBrand();// output: HondagetBrand();// output: Nissan

Although myCar.getBrand() the getBrand() same function is pointed to, this it is different because it depends on getBrand() which context is called.

We already know what the object's method is, and in the function this it is bound to that object.

In the above code, the first function call corresponds to the myCar object, and the second time corresponds window to "at this time getBrand() equivalent to window.getBrand() ". Therefore, different contexts produce different results.

Invoke context

Below, let's look at the points in the different contexts this .

Global scope (Globals scope)

All JavaScript runtimes have a unique global object. In the browser, the global object is window . and inside node. js is global .

In the global execution context (code outside any function), the this global object is pointed to, whether or not in strict mode ( strict mode ).

Local scope (local scope)

In a function, it this depends on how the function is called. In three different situations:

1. Use in simple function calls this

The first scenario is to invoke a separate function directly.

function simpleCall(){  console.log(this);}simpleCall();// output: the Window object

In this scenario, the this value is not set by the call. Because the code is not running in strict mode and this must be an object, his value defaults to the global object.

If it is under strict mode (strict mode), what value is set when entering the execution context. If not specified, then it is always undefined , as follows:

function simpleCall(){  "use strict";  console.log(this);}simpleCall();// output: undefined
2. Use in the object's method (object ' s) this

Save the function as a property of the object, which translates into a method that can be called by an object. When a function is called as a method of an object, the this value inside is set to the object that invokes the method.

var message = {  content: "I‘m a JavaScript Ninja!",  showContent: function() {    console.log(this.content);  }};message.showContent();   // output: I‘m a JavaScript Ninja!

showContent()Is message a method of an object, so this is this.content equivalent to message.content .

3. Using in the constructor (Constructor function) this

We can new call the function by operator. In this case, the function becomes a constructor (that is, an object factory). Unlike the simple function call and method call discussed earlier, the constructor call passes in a completely new object as this the value, and implicitly returns the newly constructed object as the result "in short, the memory of the newly constructed object is assigned by the new operator, and the constructor simply does some initialization work."

When a function is used as a constructor (by new keyword), its value is this bound to the newly created object. If the keyword is not used new , then he is just a normal function that this will point to the window object.

function Message(content){  this.content = content;  this.showContent = function(){    console.log(this.content);  };}var message = new Message("I‘m JavaScript Ninja!");message.showContent();// output: I‘m JavaScript Ninja!

In the example above, there is a constructor called Message() . newa completely new object is created by using the operator, named message . It also passes to the constructor a string that acts as a property of the new object content . This string can be seen successfully in the last line of code, because it this points to the newly created object instead of the constructor itself.

How to use them correctly this

In this section, we will learn some this of the internal mechanisms that determine behavior.

In JavaScript, all functions are objects, so functions can also have their own methods. All functions have two methods, which are apply () and call (). 。 We can use these two methods to change the context of the function, at all times valid, to set this the value explicitly.

apply()The method receives two parameters: the first is the object to be set to this , the second parameter is optional, and if you want to pass in a parameter, the second argument that is the array is encapsulated apply() .

call()The method apply() is basically the same, except that the argument is not an array, but instead it is separated by a single appended to the back.

Here's a Walkthrough:

function warrior(speed, strength){  console.log(    "Warrior: " + this.kind +    ", weapon: " + this.weapon +    ", speed: " + speed +    ", strength: " + strength  );}var warrior1 = {  kind: "ninja",  weapon: "shuriken"};var warrior2 = {  kind: "samurai",  weapon: "katana"};warrior.call(warrior1, 9, 5);// output: Warrior: ninja, weapon: shuriken, speed: 9, strength: 5warrior.apply(warrior2, [6, 10]);// output: Warrior: samurai, weapon: katana, speed: 6, strength: 10

Here, we have a factory function warrior() that creates different types of warrior (Warriors) by passing in different warrior objects. So, inside the factory function, it this will point to call() the object we passed and/or apply() passed in.

In the first function call, we use the call() method to this set the object and pass in warrior1 the additional parameters that are required, separated by commas. In the second function call, it is almost the same, just passing in the warrior2 object and encapsulating the necessary arguments as an array.

In call() addition apply() to and, the ECMAScript 5 also adds the bind () method, which can also be used bind to bind objects by means of a method when calling a function or method this . Let's look at the following example:

function warrior(kind){  console.log(    "Warrior: " + kind +    ". Favorite weapon: " + this.weapon +    ". Main mission: " + this.mission  );}var attributes = {  weapon: "shuriken",  mission: "espionage"};var ninja = warrior.bind(attributes, "ninja");ninja();// output: Warrior: ninja. Favorite weapon: shuriken. Main mission: espionage

In this example, the bind() method is used in a similar way, but warrior.bind() a new function is created (the method body and scope are the warrior() same), and the original function is not changed warrior() . The function of the new function is the same as the old one, just bound to the attributes object.

" bind method and call , apply the difference is that bind() after the function is not executed, can be passed to other functions, at some appropriate time to invoke the"

Summarize

So, that's this about the same thing as the knowledge. As a beginner, mastering these you are enough to use it correctly, more confidence in yourself! Of course, in the process of use may also have some problems will bother you, then, welcome to read the next article Master JS " this " (ii).

Recommended Reading

Nanyi Teacher: ECMAScript 6 Getting Started

Some learning summaries of cnblog:javascript context and scope

Infoq: ES6 (1~10) series

babeljs-es6:https://babeljs.io/repl/

Master JS in the " this " (a)

Master js " this " (ii)

RELATED LINKS

Original link: Revealing the Inner workings of JavaScript ' s "This" Keyword

Original date: May 01, 2015

Translation Date: September 17, 2015

Author: Anchor Http://blog.csdn.net/renfufei

Master JS in the "This" (a)

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.