新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
JavaScript類和繼承:this屬性
this屬性表示當前對象,如果在全局作用范圍內使用this,則指代當前頁面對象window; 如果在函數(shù)中使用this,則this指代什么是根據(jù)運行時此函數(shù)在什么對象上被調用。 我們還可以使用apply和call兩個全局方法來改變函數(shù)中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>
函數(shù)中的this屬性是在運行時決定的,而不是函數(shù)定義時,如下:
- // 定義一個全局函數(shù)
- function foo() {
- console.log(this.fruit);
- }
- // 定義一個全局變量,等價于window.fruit = "apple";
- var fruit = "apple";
- // 此時函數(shù)foo中this指向window對象
- // 這種調用方式和window.foo();是完全等價的
- foo(); // "apple"
- // 自定義一個對象,并將此對象的屬性foo指向全局函數(shù)foo
- var pack = {
- fruit: "orange",
- foo: foo
- };
- // 此時函數(shù)foo中this指向window.pack對象
- pack.foo(); // "orange"
全局函數(shù)apply和call可以用來改變函數(shù)中this屬性的指向,如下:
- // 定義一個全局函數(shù)
- 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兩個函數(shù)的作用相同,唯一的區(qū)別是兩個函數(shù)的參數(shù)定義不同。
因為在JavaScript中函數(shù)也是對象,所以我們可以看到如下有趣的例子:
- // 定義一個全局函數(shù)
- function foo() {
- if (this === window) {
- console.log("this is window.");
- }
- }
- // 函數(shù)foo也是對象,所以可以定義foo的屬性boo為一個函數(shù)
- 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.
- // 可以看到函數(shù)中this的指向調用函數(shù)的對象
- foo.boo(); // this is foo.
- // 使用apply改變函數(shù)中this的指向
- foo.boo.apply(window); // this is window.
文章名稱:JavaScript類和繼承:this屬性
文章轉載:http://www.5511xx.com/article/cdejisp.html


咨詢
建站咨詢
