1. 程式人生 > 其它 >JavaScript之this關鍵字

JavaScript之this關鍵字

技術標籤:前端

示例程式碼1

  先來看一段this關鍵字的程式碼

var name="outer";
var foo={
	name:"inner",
	getName:function(){
		console.log(this.name);
		return function() {
			console.log(this.name);
		}
	}
};
foo.getName()();

在這裡插入圖片描述
  可以看到第二個 this 關鍵字輸出的是全域性變數,在理解的時候,可以理解為下面的這個過程。

// foo.getName()();等價於下面的語句
var f=foo.getName(); console.log(f); f();

在這裡插入圖片描述

示例程式碼2

<body>
	<button type="button" onclick="test1(this);">按鈕1</button>
	<button type="button" onclick="javascript:test2();">按鈕2</button>
	<script type="text/javascript" src=
"./studyThis.js"> function test1(a) { console.log(a); } function test2() { console.log(this); } </script> </body>

在這裡插入圖片描述
  在標籤中的 js 方法中的 this 指的是這個標籤。
  而在 test2 方法中使用的 this 是當前呼叫 test2 方法的物件,在上面的程式碼中,呼叫 test2 方法的是 Window 物件。