Home  >  Article  >  Web Front-end  >  What is the use of this in js? Usage of this keyword in js (with code)

What is the use of this in js? Usage of this keyword in js (with code)

不言
不言Original
2018-08-17 13:45:291970browse

The content of this article is about what is the use of this in js? The usage of this keyword in js (with code). The article introduces the understanding of this in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, we must understand the several ways to call functions in JS:
1. Ordinary function call
2. Call as a method
3. Call as a constructor
4. Use the apply/call method to call
5.Function.prototype.bind method
6.es6 arrow function
Points: No matter how the function is called, who calls this function or method , this keyword points to whom, keep this in mind. !important

Below I will explain each method with examples!

1.Usage of this keyword: ordinary function call

(function fun(){
        this.name="segmentfault";
        console.log(this);  //window
        console.log(this.name);  //segmentfault        
})()
console.log(window.name);  //segmentfault  由此可见name属性属于window的属性。

In this code, the fun function is called as an ordinary function. In fact, fun is used as the global object window It is called by a method (everyone should know this), that is, window.fun(); so here the window object calls the fun method, then this in the fun function refers to the window, and the window also has another An attribute name, the value is segmentfault.

2.The usage of this keyword is as a method to call

var name="segmentfault";
var fun ={

name:"segmentfault-A",
showName:function(){
    console.log(this.name);  //输出  segmentfault-A
}

}
fun.showName();
//Here is the fun object calling the showName method. Obviously this keyword points to the fun object, so name

will be output.

var funA = fun.showName;
funA(); //Output segmentfault
//Here the fun.showName method is assigned to the funA variable. At this time, the funA variable is equivalent to an attribute of the window object, so When showNameA() is executed, it is equivalent to window.funA(), that is, the window object calls the funA method, so the this keyword points to window
Let’s look at it another way:

var funA={
    name:"segmentfault",
    showName:function(){
        console.log(this.name);
    }
}
var funB={
    name:"segmentfault-A",
    sayName:funA.showName
}

funB.sayName();  //输出 segmentfault-A
//虽然showName方法是在funA这个对象中定义,但是调用的时候却是在funB这个对象中调用,因此this对象指向funB

3.this The usage of the keyword is to call the constructor

function fun(name){
    this.name=name;
}
var funA = fun("segmentfault");   
console.log(funA.name); // 输出  undefined
console.log(window.name);//输出  segmentfault
//上面代码没有进行new操作,相当于window对象调用fun("segmentfault")方法,那么this指向window对象,并进行赋值操作window.name="segmentfault".

var funB=new fun("segmentfault");
console.log(funB.name);// 输出 segmentfault

4. The usage of this keyword is to call the call/apply method

Function in JS It is also an object, so functions also have methods. Inherited from Function.prototype to the Function.prototype.call/Function.prototype.apply method
The biggest function of the call/apply method is to change the pointing of this keyword.

Obj.method.apply( AnotherObj,arguments);

var name="segmentfault-A";
var fun={
    name:"segmentfault",
    showName:function(){
        console.log(this.name);
    }
}
fun.showName.call(); //输出 "segmentfault-A"
//这里call方法里面的第一个参数为空,默认指向window。
//虽然showName方法定义在fun对象里面,但是使用call方法后,将showName方法里面的this指向了window。因此最后会输出"segmentfault-A";
function FruitA(n1,n2){
    this.n1=n1;
    this.n2=n2;
    this.change=function(x,y){
        this.n1=x;
        this.n2=y;
    }
}

var fruitA = new FruitA("cheery","banana");
var FruitB={
    n1:"apple",
    n2:"orange"
};
fruitA.change.call(FruitB,"pear","peach");

console.log(FruitB.n1); //输出 pear
console.log(FruitB.n2);// 输出 peach

FruitB calls the change method of fruitA and binds this in fruitA to the object FruitB.

5. Function.prototype.bind() method for usage of this keyword

 var name="segmentfault-A";
function fun(name){
    this.name=name;
    this.sayName=function(){
        setTimeout(function(){
            console.log("my name is "+this.name);
        },50)
    }
}
var funA = new fun("segmentfault");
funA.sayName()  //输出  “my name is segmentfault-A”;
//这里的setTimeout()定时函数,相当于window.setTimeout(),由window这个全局对象对调用,因此this的指向为window, 则this.name则为segmentfault-A

Use bind() method below to output segmentfault

var name="segmentfault";
function fun(name){
    this.name=name;
    this.sayName=function(){
        setTimeout(function(){
            console.log("my name is "+this.name);
        }.bind(this),50)  //注意这个地方使用的bind()方法,绑定setTimeout里面的匿名函数的this一直指向fun对象
    }
}
var funA = new fun("segmentfault");
funA.sayName()  //输出  “my name is segmentfault”;
//这里的setTimeout()定时函数,相当于window.setTimeout(),由window这个全局对象对调用,因此this的指向为window, 则this.name则为segmentfault

Here setTimeout(function(){console.log(this.name)}.bind(this),50);, the anonymous function creates a new function after using the bind(this) method, no matter where this new function is Local execution, this points to fun, not window, so the final output is "my name is segmentfault" instead of "my name is segmentfault-A"

A few other things to note:
setTimeout/setInterval/When the anonymous function is executed, this points to the window object by default, unless the point of this is manually changed. In "JavaScript Advanced Programming", it is written: "The timeout call code (setTimeout) is executed in the global scope, so the value of this in the function points to the window object in non-strict mode, and in strict mode In mode, it points to undefined". This article is all in non-strict mode.

6. Eval function for usage of this keyword

When this function is executed, this is bound to the object in the current scope

var name="segmentfault-A";
var fun = {
    name:"segmentfault",
    showName:function(){
        eval("console.log(this.name)");
    }
}

fun.showName();  //输出  "segmentfault"

var a = fun.showName;
a();  //输出  "segmentfault-A"

7. Arrow function for usage of this keyword

The this point in es6 is fixed and always points to the external object, because the arrow function does not have this, so it cannot instantiate new by itself. At the same time, you cannot use call, apply, bind and other methods to change the pointer of this.

 function Timer() {
    this.seconds = 0;
    setInterval( () => this.seconds ++, 1000);
} 

var timer = new Timer();

setTimeout( () => console.log(timer.seconds), 3000);

// 3
   // 在构造函数内部的setInterval()内的回调函数,this始终指向实例化的对象,并获取实例化对象的seconds的属性,每1s这个属性的值都会增加1。否则最后在3s后执行setTimeOut()函数执行后输出的是0

Related recommendations:

Understanding of this keyword in js

About this keyword in js Understanding_javascript skills

A question about js this keyword_javascript skills

The above is the detailed content of What is the use of this in js? Usage of this keyword in js (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn