[Javascript] Object_this keyword

Suyeon·2020년 8월 21일
0

Javascript

목록 보기
4/31

1️⃣ "this" in method

  • To access the object, a method can use the this keyword.
let user = {
  name: "John",
  age: 30,
  sayHi() {
    alert(this.name);
  }
};

user.sayHi(); // John

✔️ Risky way

  • It’s possible to access the object without this, by referencing it via the outer variable.
let user = {
  name: "John",
  age: 30,
  sayHi() {
    alert( user.name ); 
  }
};

let admin = user;
user = null; 
admin.sayHi(); // Error!

✔️ How to declare a method?

// (*) Better
let user = {
  sayHi() { 
    alert("Hello");
  }
};

// (**) 
let user = {
  sayHi: function() {
    alert("Hello");
  }
};

2️⃣ “this” is not bound

  • "this" can be used in any function. Because the value of "this" is evaluated during the run-time.
  • In regular functions the this keyword represented the object that called the function,
let user = { name: "John" };
let admin = { name: "Admin" };

function sayHi() {
  alert( this.name ); // no syntax error
}

user.f = sayHi;
admin.f = sayHi;

user.f(); // John  
admin.f(); // Admin

3️⃣ Arrow functions have no “this”

  • It’s taken from the outer “normal” function (outer context).
  • In arrow functions the this keyword always represents the object that defined the arrow function.
let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Ilya
profile
Hello World.

0개의 댓글