this表示當(dāng)前對(duì)象,如果在全局作用范圍內(nèi)使用this,則指代當(dāng)前頁面對(duì)象window; 如果在函數(shù)中使用this,則this指代什么是根據(jù)運(yùn)行時(shí)此函數(shù)在什么對(duì)象上被調(diào)用。 我們還可以使用apply和call兩個(gè)全局方法來改變函數(shù)中this的具體指向。
先看一個(gè)在全局作用范圍內(nèi)使用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>
函數(shù)中的this是在運(yùn)行時(shí)決定的,而不是函數(shù)定義時(shí),如下:
// 定義一個(gè)全局函數(shù) function foo() { console.log(this.fruit); } // 定義一個(gè)全局變量,等價(jià)于window.fruit = "apple"; var fruit = "apple"; // 此時(shí)函數(shù)foo中this指向window對(duì)象 // 這種調(diào)用方式和window.foo();是完全等價(jià)的 foo(); // "apple" // 自定義一個(gè)對(duì)象,并將此對(duì)象的屬性foo指向全局函數(shù)foo var pack = { fruit: "orange", foo: foo }; // 此時(shí)函數(shù)foo中this指向window.pack對(duì)象 pack.foo(); // "orange"
全局函數(shù)apply和call可以用來改變函數(shù)中this的指向,如下:
// 定義一個(gè)全局函數(shù) function foo() { console.log(this.fruit); } // 定義一個(gè)全局變量 var fruit = "apple"; // 自定義一個(gè)對(duì)象 var pack = { fruit: "orange" }; // 等價(jià)于window.foo(); foo.apply(window); // "apple" // 此時(shí)foo中的this === pack foo.apply(pack); // "orange" 注:apply和call兩個(gè)函數(shù)的作用相同,唯一的區(qū)別是兩個(gè)函數(shù)的參數(shù)定義不同。
因?yàn)樵贘avaScript中函數(shù)也是對(duì)象,所以我們可以看到如下有趣的例子:
// 定義一個(gè)全局函數(shù) function foo() { if (this === window) { console.log("this is window."); } } // 函數(shù)foo也是對(duì)象,所以可以定義foo的屬性boo為一個(gè)函數(shù) foo.boo = function() { if (this === foo) { console.log("this is foo."); } else if (this === window) { console.log("this is window."); } }; // 等價(jià)于window.foo(); foo(); // this is window. // 可以看到函數(shù)中this的指向調(diào)用函數(shù)的對(duì)象 foo.boo(); // this is foo. // 使用apply改變函數(shù)中this的指向 foo.boo.apply(window); // this is window.
我們已經(jīng)在第一章中使用prototype模擬類和繼承的實(shí)現(xiàn)。 prototype本質(zhì)上還是一個(gè)JavaScript對(duì)象。 并且每個(gè)函數(shù)都有一個(gè)默認(rèn)的prototype屬性。
如果這個(gè)函數(shù)被用在創(chuàng)建自定義對(duì)象的場(chǎng)景中,我們稱這個(gè)函數(shù)為構(gòu)造函數(shù)。 比如下面一個(gè)簡單的場(chǎng)景:
// 構(gòu)造函數(shù) function Person(name) { this.name = name; } // 定義Person的原型,原型中的屬性可以被自定義對(duì)象引用 Person.prototype = { getName: function() { return this.name; } } var zhang = new Person("ZhangSan"); console.log(zhang.getName()); // "ZhangSan"
新聞熱點(diǎn)
疑難解答
圖片精選