在 JavaScript 裡,this 指向 window,在 function 中, this 指向呼叫它的地方。
例如:
// Window
window.name = "Amy";
console.log(this.name); // Amy
console.log(this); // Window Object
// Object
let Helen = {
age:24,
sayAge(){
console.log("I am " + this.age + " years old.")
}
};
Helen.sayAge(); // I am 24 years old.
在 sayAge() 裡面的 this 取決於呼叫它的地方,sayAge() 是在 Helen 這個 object 裡被定義的,所以 this 就代表這個 object,this.age 就會是 24。
this 也能改變物件的值,例如:
let Helen = {
age:24,
sayAge(){
console.log("I am " + this.age + " years old.")
}
};
Helen.age = 25;
Helen.sayAge(); // I am 25 years old.
箭頭函式語法簡單,和傳統函式比,可以少打很多字,也讓程式碼較好閱讀,在箭頭函式中,沒有自己的 this,所以箭頭函式中的 this 永遠指向函式被定義時所在的作用域中的 this 值。
過去我們寫函式的方式如下:
function sayHi(){
console.log("Hi");
}
sayHi(); // Hi
將上面例子改成箭頭函式:
const sayHi = () => {
console.log("Hi")
}
sayHi(); // Hi
const sayHi = () => {
return "Hi";
}
sayHi(); // Hi
上面的例子也可以簡化成下面這樣:
const sayHi = () => "Hi";
sayHi(); // Hi
let count = (x) => {
console.log(x + 1)
}
count(3); // 4
參數省略 () 後:
let count = x => {
console.log(x + 1)
}
count(3); // 4
sayHi("Gina");
let sayHi = (name) => {
console.log("Hi" + name)
}
執行上面的程式碼,會得到 Uncaught RefernceError 不能在定義前執行的錯誤提示
下面的程式碼因為 this 指向 window,會回傳 undefined,這時我們就可以使用 bind,call or apply
let Helen = {
name:"Helen",
age:24,
}
function getPerson(){
console.log(this.age); // undefined
}
getPerson();
let Helen = {
name:"Helen",
age:24,
}
function getPerson(){
console.log(this);
console.log(this.age);
}
getPerson();
// Window Object
// undefined
// 使用 bind 綁定
let newfn = getPerson.bind(Helen);
newfn();
// {name:"Helen",age:24,}
// 24
let Helen = {
name:"Helen",
age:24,
}
function getPerson(){
console.log(this);
console.log(this.age);
}
getPerson.call(Helen);
// {name:"Helen",age:24,}
// 24
如果 function 內有參數,則直接在括號後面加上去
let Helen = {
name:"Helen",
age:24,
}
function getPerson(country,sex){
console.log(this);
console.log(this.age);
console.log("I am from " + country + ".I am " +sex );
}
getPerson.call(Helen,"Taiwan","Female");
// {name:"Helen",age:24,}
// 24
// I am from Taiwan.I am Female
let Helen = {
name:"Helen",
age:24,
}
function getPerson(country,sex){
console.log(this);
console.log(this.age);
console.log("I am from " + country + ".I am " +sex );
}
getPerson.apply(Helen,["Taiwan","Female"]);
// {name:"Helen",age:24,}
// 24
// I am from Taiwan.I am Female