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
“this” in methods
很常見的是物件的方法需要物件裡的資料。
“this” is not bound
this 的值不是固定的,是在執行時被決定的。
Calling without an object: this == undefined
this == undefinednon strict 的情形下,this 是 global object 在 browser 為 window 。
Internals: Reference Type
為了讓 user.hi() 有效,JavaScript 內部演算 ' . ' 返回的不是函式,而是一個特殊的值 Reference Type
Arrow functions have no “this”
Last updated
Was this helpful?