Object methods, "this"

Method examples

函式為物件的屬性叫做方法

// funciton expression
let user = {
  name: "John",
  age: 30
};

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

user.sayHi(); // Hello!

// same function declaration
let user = {
  // ...
};

// first, declare
function sayHi() {
  alert("Hello!");
};

// then add as a method
user.sayHi = sayHi;

user.sayHi(); // Hello!

Method shorthand

// these objects do the same

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

// method shorthand looks better, right? shorter is preffered
user = {
  sayHi() { // same as "sayHi: function()"
    alert("Hello");
  }
};

“this” in methods

很常見的是物件的方法需要物件裡的資料。

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

  sayHi() {
    alert(this.name);
  }

};

user.sayHi(); // John

// 可以用物件名稱代替 this,但若有其他物件指向同一個記憶體,之後可能發生錯誤。
let user = {
  name: "John",
  age: 30,

  sayHi() {
    alert( user.name ); // leads to an error
  }

};


let admin = user;
user = null; // overwrite to make things obvious

admin.sayHi(); // Whoops! inside sayHi(), the old name is used! error!

“this” is not bound

this 的值不是固定的,是在執行時被決定的。

let user = { name: "John" };
let admin = { name: "Admin" };

function sayHi() {
  alert( this.name );
}

// use the same function in two objects
user.f = sayHi;
admin.f = sayHi;

// these calls have different this
// "this" inside the function is the object "before the dot"
user.f(); // John  (this == user)
admin.f(); // Admin  (this == admin)

admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)

Calling without an object: this == undefined

non strict 的情形下,this 是 global object 在 browser 為 window 。

function sayHi() {
  alert(this);
}

sayHi(); // undefined

Internals: Reference Type

let user = {
  name: "John",
  hi() { alert(this.name); },
  bye() { alert("Bye"); }
};

user.hi(); // John (the simple call works)

// now let's call user.hi or user.bye depending on the name
(user.name == "John" ? user.hi : user.bye)(); // Error!

// put method in separate line it can't work
let user = {
  name: "John",
  hi() { alert(this.name); }
}

// split getting and calling the method in two lines
let hi = user.hi;
hi(); // Error, because this is undefined

為了讓 user.hi() 有效,JavaScript 內部演算 ' . ' 返回的不是函式,而是一個特殊的值 Reference Type

// Reference Type value
(user, "hi", true)

Arrow functions have no “this”

// arrow() 的 this 來自 sayHi()
let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Ilya

Last updated