Object methods "this"

Object methods "this"

Let user = {
  name: "John",
  age: 30,

  sayHi() {
*!*
    alert(this.name);
*/!*
  }

};

user.sayHi(); // John

To access the object, a method can use the this keyword.

The value of this is the object "before dot", the one used to call the method.

Method examples

Let user = {
  name: "John",
  age: 30
};

*!*
user.sayHi = function() {
  alert("Hello!");
};
*/!*

user.sayHi(); // Hello!

A function that is the property of an object is called its method.

Method shorthand

// these objects do the same

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

// method shorthand looks better, right?
let user = {
*!*
  sayHi() { // same as "sayHi: function()"
*/!*
    alert("Hello");
  }
};

There exists a shorter syntax for methods in an object literal.

Object methods "this" — Structure map

Clickable & Draggable!

Object methods "this" — Related pages: