this in 7 cases

Global Context:

  (outside of any function), this refers to the global object,

  which is often window in a browser or global in Node.js.

console.log(this===window);// true in a browser

Function Context: the value of this depends on how the function is called.

  a standalone function (not as a method), this typically refers to the global object.

  called as a method of an object, this refers to the object itself.

function greetGlobal(){console.log(`Hello, ${this.name}`);}

const name="Bob";

greetGlobal();// Output: "Hello, undefined" (in a browser), or "Hello, global" (in Node.js)

const obj={

name:"Alice",

greet:function(){console.log(`Hello, ${this.name}`);}

};

obj.greet();// Output: "Hello, Alice"

Constructor Functions:

  When a function is used as a constructor to create objects with the new keyword, this refers to the newly created object.

function Person(name){this.name=name;}

const person=new Person("Charlie");

console.log(person.name);// Output: "Charlie"

Explicit Binding:

  You can explicitly bind this to a specific object using methods like call(), apply(), or bind().

const person={

name:"David",

greet:function(){console.log(`Hello, ${this.name}`);}

};

const anotherPerson={name:"Eve"};

person.greet.call(anotherPerson);// Output: "Hello, Eve"

Arrow Functions:

  Arrow functions capture the value of this from their surrounding lexical (enclosing) context. They do not have their own this context.

const obj={

name:"Frank",

greet:()=>{console.log(`Hello, ${this.name}`);}

};

obj.greet();// Output: "Hello, undefined" (uses the global `this` since arrow functions don't have their own `this`)

Event Handlers:

  In event handler functions (e.g., onClick), this usually refers to the element that triggered the event.

const button=document.querySelector('button');

button.addEventListener('click',function(){

console.log(this);// `this` refers to the button element

});


https://zellwk.com/blog/this/

this in global context

this in a simple function

this in an object method

this in object construction

this in an arrow function

this in an event listener


this in global context -> window

This in object construction

When you create a new instance of an object with the new keyword, this refers to the instance.

This in an object method

Methods are fancy words for functions that are associated with an object, like this:

This in an object method->object

This in a simple function

Simple functions are functions you know extremely well; like the one below. 

Anonymous functions written in the same form are also considered simple functions.

function hello () { // say hello!}

On browsers, this is always set to Window in a simple function. The same is true even if you call a simple function in an object method.

simple function->runtime binding

Unfortunately, the change in this is unexpected for beginners. They expect this to remain the same within object methods. I got caught in it too.

To see why, consider the following code. Here, a this.speakLeet function is executed later within a setTimeout function.

this dynamic binding: analyze function call stack

Unfortunately, the code above results in an error. The error occurs because this is set to Window in the setTimeout function. Window does not have a speakLeet method.

One quick fix is to create a variable that stores the reference to the this. This variable is often called self or that.

create a variable that stores the reference to the this

A second way to fix this problem is to use the new ES6 arrow functions, which brings us to the next context.

This in arrow functions

this in an arrow function is always the same as this around it (in its immediate scope). So, if you use arrow functions within an object method, the this context stays as the object, not Window.

With arrow functions, the speakLeet example could be written in the following way:

arrow functions within an object method

A third way to change the value of this within any function is to use either bind, call or apply. We’ll look at bind later in the article, and call and apply another time. But first, let’s go through the final context — event listeners.

This in event listeners

this is set to the element that fired the event in an event listener:

let button = document.querySelector('button')

button.addEventListener('click', function () { 

     console.log(this) // button

})

When creating more complex components, you may find yourself creating event listeners within methods.

Since this refers to the element in the event listener, if you need to activate another method, you need to provide a reference to the object with.

this refers to element in the event listener, need to store a reference

Alternatively, you can use an arrow function. If you do so, you can still get the element with event.currentTarget.

arrow function in event handler uses lexical this; access element by event.currentTarget

But both methods aren’t good enough to help you remove event listeners when the need arises, both are anonymous functions.

To remove an event listener, the callback passed as the second value needs to be a named function:

function someFunction () { 

 console.log('do something') 

 // Removes the event listener. 

 document.removeEventListener('click', someFunction)

}

document.addEventListener('click', someFunction)

If you need this to reference the object in an event listener, you need to use bind to manually create a this context.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容