iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

追憶JS年華系列 第 19

Day-19 This

  • 分享至 

  • xImage
  •  

this 可說是 JavaScript中最複雜的概念,它是一個內部物件,代表函式(function)執行時所屬的物件。

this 指向的值通常是「呼叫函式的物件」。隨著呼叫的物件不同,執行(如console.log)結果也會不同。

本篇彙整 this 各大規則,做為其他說明資源之補充。

規則:有沒有用 new

用new會建立空物件。印出整齊的變數參數。
不加new會印出global。

function hello() {
	this.name = "13"
	this.age = 18
	console.log(this);
}

new hello() //hello()

規則:是否使用「嚴格模式」

  • 以 “use strict” 開啟嚴格模式
  • 原本this判定為globe會改判undefine
    • 可寫在文件最上方或function最上方。
    • 因引用外部function頻繁,不建議開啟。
function hello() {
	"use strict"
	console.log(this);
}

hello()

規則:誰呼叫,誰就是 this

例: 此時hello() 相當於 global.hello(),所以接第3條

function hello() {
	console.log(this) //global
}

hello()

若確定是誰(變數)呼叫(this),可用this取代變數名稱:

const hero = {
	name: "Keaton"
	attack: function() {
		console.log("hi, " + hero.name);
		console.log("hi, " + this.name);
		// console.log(this)
	}
}

hero.attack()

規則:前面沒有人,this -> global

沒有人呼叫sayMyName(),故印出global全域變數
但若”悟空”改為let宣告,就抓不到global,改印出undefined

var name = "蝙蝠俠"

function sayMyName() {
	var name = "羅賓"
	console.log(this.name);
}

sayMyName() //印出"蝙蝠俠"

規則:是否有使用 Call / Apply / Bind(高階函式)

Call綁定

不會創造function。可以額外帶參數。
例:三個參數各給一個console.log

function attack(xx, yy, zz) {
	console.log(xx);
	console.log(yy);
	console.log(zz);
	console.log(`${this.name} 使用絕招 ${this.action}`);
}

const hero = {
	name: "蝙蝠俠",
	action: "鈔能力",
}

attack.call(hero, 1, 2, 3)

Apply綁定

不會創造function。可以額外帶參數,但須為物件(陣列 [1, 2, 3, 4, 5])。

Bind綁定

回傳新function,改變this的指向:

const function.bind(hero) //將this指向hero變數

heroAttack() //印出"蝙蝠俠 使用絕招 鈔能力"

呼叫新function時可帶參數:

const function.bind(hero) //將this指向hero變數

heroAttack(1, 2, 3) 

上一篇
Day-18 閉包
下一篇
Day-20 OOP與抽象類別
系列文
追憶JS年華30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言