轉自 http://developer.51cto.com/art/200902/111044.htm
- 本文介紹了JavaScript裏面的this屬性。這個屬性是理解JavaScript類和繼承的重要基礎。
this屬性表示當前對象,如果在全局作用範圍內使用this,則指代當前頁面對象window; 如果在函數中使用this,則this指代什麼是根據運行時此函數在什麼對象上被調用。 我們還可以使用apply和call兩個全局方法來改變函數中this的具體指向。
先看一個在全局作用範圍內使用this的例子:
- <
script
type
=
"text/javascript"
>
- console.log(
this
=== window); // true - console.log(
window.alert
=== this.alert); // true - console.log(this.parseInt("021", 10)); // 10
- <
/script
>
函數中的this屬性是在運行時決定的,而不是函數定義時,如下:
- // 定義一個全局函數
- function foo() {
- console.log(
this
.fruit); - }
- // 定義一個全局變量,等價於window.fruit = "apple";
- var fruit =
"apple"
; - // 此時函數foo中this指向window對象
- // 這種調用方式和window.foo();是完全等價的
- foo();
// "apple"
-
- // 自定義一個對象,並將此對象的屬性foo指向全局函數foo
- var pack = {
- fruit:
"orange"
, - foo: foo
- };
- // 此時函數foo中this指向window.pack對象
- pack.foo();
// "orange"
-
全局函數apply和call可以用來改變函數中this屬性的指向,如下:
- // 定義一個全局函數
- function foo() {
- console.log(
this
.fruit); - }
-
-
// 定義一個全局變量
- var fruit =
"apple"
; -
// 自定義一個對象
- var pack = {
- fruit:
"orange"
- };
-
-
// 等價於window.foo();
- foo.apply(window);
// "apple"
-
// 此時foo中的this === pack
- foo.apply(pack);
// "orange"
-
注:apply和call兩個函數的作用相同,唯一的區別是兩個函數的參數定義不同。
因爲在JavaScript中函數也是對象,所以我們可以看到如下有趣的例子:
- // 定義一個全局函數
- function foo() {
-
if
(
this
=== window) { - console.log(
"this is window."
); - }
- }
-
- // 函數foo也是對象,所以可以定義foo的屬性boo爲一個函數
- foo.boo = function() {
-
if
(
this
=== foo) { - console.log(
"this is foo."
); - }
else
if
(
this
=== window) { - console.log(
"this is window."
); - }
- };
- // 等價於window.foo();
- foo();
// this is window.
-
- // 可以看到函數中this的指向調用函數的對象
- foo.boo();
// this is foo.
-
- // 使用apply改變函數中this的指向
- foo.boo.apply(window);
// this is window.