markdown 这是JS中的

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 这是JS中的相关的知识,希望对你有一定的参考价值。

## “this” in Global Environment

The working mechanism of this is not always easy to understand. To understand how this works, we will start looking at this in different environments. Let’s start by looking at the global environment first.

At the global level, this is equivalent to a global object called global.

```sh
> this === global
true
```

But this is true only inside node. If we try to run this same code inside a JavaScript file, we will get the output as false.

To test this, create a file called index.js with the following code inside it:
```sh
console.log(this === global);
```

Then run this file using the node command:

```sh
$ node index.js
false
```

The reason for this is that inside a JavaScript file, this equates to module.exports and not global.

## “this” inside Functions
The value of this inside a function is usually defined by the function’s call. So, this can have different values inside it for each execution of the function.
In your index.js file, write a very simple function that simply checks if this is equal to the global object.
```sh
function rajat() {
  console.log(this === global)
}

rajat()
```
If we run this code using node, we will the output as true. But we add "use strict" at the top of the file and run it again, we will get a false output because now the value of this is undefined.

To further explain this, let’s create a simple function that defines a Superhero’s real name and hero name.

```sh
function Hero(heroName, realName) {
  this.realName = realName;
  this.heroName = heroName;
}

const superman= Hero("Superman", "Clark Kent");
console.log(superman);
```
Note that this function is not written in strict mode. Running this code in node will not get us the value of “Superman” and “Clark Kent” as we expected, but it will instead just give us an undefined.

The reason behind this is that since the function is not written in strict mode, this refers to the global object.

If we run this code in strict mode, we will get an error because JavaScript does not allow us to assign properties realName and heroName to undefined. This actually is a good thing because it prevents us from creating global variables.

Lastly, writing the function’s name in uppercase means that we need to call it as a constructor using the new operator. Replace the last two lines of the above code snippet with this:

```sh
const superman = new Hero("Superman", "Clark Kent");
console.log(superman);
```

Run the node index.js command again, and you will now get the expected output.
## “this” inside constructors
JavaScript does not have any special constructor functions. All we can do is convert a function call into a constructor call using new operator as shown in the above section.

When a constructor call is made, a new object is created and set as the function’s this argument. The object is then implicitly returned from the function, unless we have another object that is being returned explicitly.

Inside the hero function write the following return statement:

```sh
return {
  heroName: "Batman",
  realName: "Bruce Wayne",
};
```

If we run the node command now, we will see that the above return statement overwrites the constructor call.

The only scenario where the return statement doesn’t overwrite the constructor call is if the return statement tries to return anything that is not an object. In this case, the object will contain the original values.
## “this” in Object Methods

When calling a function as a method of an object, this refers to the object, which is then known as the receiver of the function call.

Here, I have a method dialogue inside an object called hero. The dialogue‘s this value then refers to hero itself. So hero here will be know as the receiver of the dialogue method’s call.

```sh
const hero = {
  heroName: "Batman",
  dialogue() {
    console.log(`I am ${this.heroName}!`);
  }
};
hero.dialogue();
```

This is very simply example. But in the real-world cases it can get very hard for our method to keep track of the receiver. Write the following snippet at the end of index.js.

```sh
const saying = hero.dialogue();
saying();
```

Here, I am storing the reference to dialogue inside another variable and calling the variable as a function. Run this with node and you will see that this returns an undefined because the method has lost track of the receiver. this now refers to global instead of hero.

The loss of receiver usually happens when we are passing a method as a callback to another. We can either solve this by adding a wrapper function or by using bind method to tie our this to a specific object.
Though a function’s this value is set implicitly, we can also call function with explicit this argument call() and apply().

Lets restructure the previous sections code snippet like this:

```sh
function dialogue () {
  console.log (`I am ${this.heroName}`);
}
const hero = {
  heroName: 'Batman',
};
```

We need to connect the dialogue function with the hero object as a receiver. To do so, we can either use call() or apply() like this:

```sh
dialogue.call(hero)
// or
dialogue.apply(hero)
```

But if you are using call or apply outside of strict mode, then passing null or undefined using call or apply will be ignored by the JavaScript engine. This is one of the reasons why it is usually suggested to always write our code in strict mode.
## bind()
When we pass a method as a callback to another function, there is always a risk of losing the intended receiver of the method, making the this argument set to the global object instead.

The bind() method allows us to permanently tie a this argument to a value. So in the below code snippet, bind will create a new dialogue function and set its this value to hero.
```sh
const hero = {
  heroName: "Batman",
  dialogue() {
    console.log(`I am ${this.heroName}`);
  }
};

setTimeOut(hero.dialogue.bind(hero), 1000);
```

By doing so, our this cannot be changed by even call or apply methods.
## Catching “this” inside an Arrow Function
Using this with an arrow function is quite different from using it with any other kind of JavaScript function. An arrow function uses the this value from its enclosing execution context, since it does have one of its own.

An arrow function permanently captures the this value, preventing apply or call from changing it later on.

To explain how this works with regards to the arrow functions, let’s write the arrow function shown below:

```sh
const batman = this;
const bruce = () => {
  console.log(this === batman);
};

bruce();
```

Here, we are storing the value of a this in a variable and then comparing the value with a this value that is inside an arrow function. Running node index.js in our terminal should give us true as output.

An arrow function’s this value cannot be set explicitly. Also, the arrow function will ignored any attempt from us at passing a value to this using methods like call, apply, and bind. An arrow function will refer to the this value that was set when the arrow function was created.

An arrow function can also not be used as a constructor. Hence, we cannot assign properties to this inside an arrow function.

So what can arrow functions do in regards to this?

Arrow functions can help us access this within a callback. To explain how this is done. Take a look at the counter object that I have written below:

```sh
const counter = {
  count: 0,
  increase() {
    setInterval(function() {
      console.log(++this.count);
    }, 1000);
  }
}

counter.increase();
```

Running this code using node index.js will only give an increase list of NaNs. This is because this.count is not referring to the counter object. It actually refers to the global object.

To make this counter work, lets rewrite it using an arrow function.

```sh
const counter = {
  count: 0,
  increase () {
    setInterval (() => {
      console.log (++this.count);
    }, 1000);
  },
};

counter.increase ();
```

Our callback now uses this binding from the increase method, and the counter now works as it should.

Note: Do not try to write this.count + 1 instead of ++this.count. The former of these two will only increase the value of count once, and return the that value on each iteration.
## “this” in Classes

Classes are one of the most important parts of any JavaScript apps. Lets see how this behaves inside a class.

A class generally contains a constructor, where this would refer to any newly created object.

But in case of methods, this can also refer to any other value if the method is called as an ordinary function. And just like a method, classes can also lose track of the receiver.

Let’s re-create the Hero functions that we have seen earlier as a class. This class will contain a constructor and a dialogue() method. Finally, we create an instance of this class and call the dialogue method.

```sh
class Hero {
  constructor(heroName) {
    this.heroName = heroName;
  }
  dialogue() {
    console.log(`I am ${this.heroName}`)
  }
}

const batman = new Hero("Batman");
batman.dialogue();
```

this inside the constructor refers to the newly created instance of that class. When we call batman.dialogue(), we invoke dialogue() as a method with batman as a receiver.

But if we store a reference to the dialogue() method, and later invoke it as a function, we once again lose the receiver of the method and the this argument now refers to undefined.

```sh
const say = batman.dialogue();
say();
```

The reason for error is that JavaScript classes are implicitly in strict mode. We are invoking say() as an function without any autobinding. To solve this, we will need to manually bind() to tie this dialogue() function to batman.

```sh
const say = batman.dialogue.bind(batman);
say();
```

We can also do this binding inside the constructor method.

以上是关于markdown 这是JS中的的主要内容,如果未能解决你的问题,请参考以下文章

markdown JS中的范围是什么?

使你的网站支持markdown

HyperDown.js 这个markdown解析器在浏览器中怎么使用

markdown Node.js中的自定义ES6错误

markdown 在使用AJAX呈现的Handlebars.js模板文件上显示平面JSON文件中的数据。

markdown 将Mapbox中的栅格加载到具有透明度的Leaflet或ArcGIS JS API中