관리 메뉴

Silver Library (Archived)

How to use 'this' keyword in JS? 본문

F4. Library of Languages/JavaScript (JS)

How to use 'this' keyword in JS?

Chesed Kim 2023. 1. 4. 17:05
반응형

The point is; how to make it like expert?

 

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

 

In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. The bind() method can set the value of a function's this regardless of how it's called, and arrow functions don't provide their own this binding (it retains the this value of the enclosing lexical context).

 

Now, the expression of this was:

const test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
};

console.log(test.func());
// expected output: 42

And function,

function getThis() {
  return this;
}

const obj1 = { name: "obj1" };
const obj2 = { name: "obj2" };

obj1.getThis = getThis;
obj2.getThis = getThis;

console.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] }
console.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }

Now, how about using this concept?

function anime() {
	return `The title of anime you addressed is ${this.title}.`
}

const alpha = {
	title: 'Neon Genesis Evangelion',
    anime
}

const beta = {
	title: 'psycho-pass',
    anime
}

alpha.anime()
// "The title of anime you addressed is Neon Genesis Evangelion."
beta.anime()
// "The title of anime you addressed is psycho-pass."

 

Do remember: how the function is the same, but based on how it's invoked, the value of this is different. This is analogous to how function parameters work.

 

Something to remember...Global Context

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.b = "MDN";
console.log(window.b); // "MDN"
console.log(b); // "MDN"

this in arrow functions

Arrow functions create closures over the this value of the enclosing execution context. In the following example, we create obj with a method getThisGetter that returns a function that returns the value of this. The returned function is created as an arrow function, so its this is permanently bound to the this of its enclosing function. The value of this inside getThisGetter can be set in the call, which in turn sets the return value of the returned function.

const obj = {
  getThisGetter() {
    const getter = () => this;
    return getter;
  },
};

We can call getThisGetter as a method of obj, which sets this inside the body to obj. The returned function is assigned to a variable fn. Now, when calling fn, the value of this returned is still the one set by the call to getThisGetter, which is obj. If the returned function is not an arrow function, such calls would cause the this value to be globalThis or undefined in strict mode.

const fn = obj.getThisGetter();
console.log(fn() === obj); // true

But be careful if you unbind the method of obj without calling it, because getThisGetter is still a method that has a varying this value. Calling fn2()() in the following example returns globalThis, because it follows the this from fn2, which is globalThis since it's called without being attached to any object.

const fn2 = obj.getThisGetter;
console.log(fn2()() === globalThis); // true

This behavior is very useful when defining callbacks. Usually, each function expression creates its own this binding, which shadows the this value of the upper scope. Now, you can define functions as arrow functions if you don't care about the this value, and only create this bindings where you do (e.g. in class methods). See example with setTimeout().


Source:

 

this - JavaScript | MDN

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

developer.mozilla.org

'F4. Library of Languages > JavaScript (JS)' 카테고리의 다른 글

Reactjs - State the time of my pc  (0) 2023.01.10