// funciton expressionlet user = { name:"John", age:30};user.sayHi=function() {alert("Hello!");};user.sayHi(); // Hello!// same function declarationlet user = {// ...};// first, declarefunctionsayHi() {alert("Hello!");};// then add as a methoduser.sayHi = sayHi;user.sayHi(); // Hello!
Method shorthand
// these objects do the sameuser = {sayHi:function() {alert("Hello"); }};// method shorthand looks better, right? shorter is preffereduser = {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 obviousadmin.sayHi(); // Whoops! inside sayHi(), the old name is used! error!
“this” is not bound
this 的值不是固定的,是在執行時被決定的。
let user = { name:"John" };let admin = { name:"Admin" };functionsayHi() {alert( this.name );}// use the same function in two objectsuser.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 。
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 worklet user = { name:"John",hi() { alert(this.name); }}// split getting and calling the method in two lineslet 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() {letarrow= () =>alert(this.firstName);arrow(); }};user.sayHi(); // Ilya