本文介紹了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);
- }
-
- var fruit = "apple";
-
-
- foo();
-
-
- var pack = {
- fruit: "orange",
- foo: foo
- };
-
- pack.foo();
-
全局函數apply和call能夠用來改變函數中this屬性的指向,以下:
-
- function foo() {
- console.log(this.fruit);
- }
-
-
- var fruit = "apple";
-
- var pack = {
- fruit: "orange"
- };
-
-
- foo.apply(window);
-
- foo.apply(pack);
-
注:apply和call兩個函數的做用相同,惟一的區別是兩個函數的參數定義不一樣。
由於在JavaScript中函數也是對象,因此咱們能夠看到以下有趣的例子:
-
- function foo() {
- if (this === window) {
- console.log("this is window.");
- }
- }
-
-
- foo.boo = function() {
- if (this === foo) {
- console.log("this is foo.");
- } else if (this === window) {
- console.log("this is window.");
- }
- };
-
- foo();
-
-
- foo.boo();
-
-
- foo.boo.apply(window);