亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript中this關(guān)鍵詞的使用技巧、工作原理以及注意事項

 更新時間:2014年05月20日 14:04:57   作者:  
在JavaScript中,this 的概念比較復雜。除了在面向?qū)ο缶幊讨?,this 還是隨處可用的。這篇文章介紹了this 的工作原理,它會造成什么樣的問題以及this 的相關(guān)例子。

要根據(jù)this 所在的位置來理解它,情況大概可以分為3種:

  1、在函數(shù)中:this 通常是一個隱含的參數(shù)。

  2、在函數(shù)外(頂級作用域中):在瀏覽器中this 指的是全局對象;在Node.js中指的是模塊(module)的導出(exports)。

  3、傳遞到eval()中的字符串:如果eval()是被直接調(diào)用的,this 指的是當前對象;如果eval()是被間接調(diào)用的,this 就是指全局對象。

  對這幾個分類,我們做了相應的測試:
  1、在函數(shù)中的this

  函數(shù)基本可以代表JS中所有可被調(diào)用的結(jié)構(gòu),所以這是也最常見的使用this 的場景,而函數(shù)又能被子分為下列三種角色:

    實函數(shù)
    構(gòu)造器
    方法

  1.1  在實函數(shù)中的this

  在實函數(shù)中,this 的值是取決于它所處的上下文的模式。

  Sloppy模式:this 指的是全局對象(在瀏覽器中就是window)。

復制代碼 代碼如下:

function sloppyFunc() {
    console.log(this === window); // true
}
sloppyFunc();

Strict模式:this 的值是undefined。

復制代碼 代碼如下:

function strictFunc() {
    'use strict';
    console.log(this === undefined); // true
}
strictFunc();

this 是函數(shù)的隱含參數(shù),所以它的值總是相同的。不過你是可以通過使用call()或者apply()的方法顯示地定義好this的值的。

復制代碼 代碼如下:

function func(arg1, arg2) {
    console.log(this); // 1
    console.log(arg1); // 2
    console.log(arg2); // 3
}
func.call(1, 2, 3); // (this, arg1, arg2)
func.apply(1, [2, 3]); // (this, arrayWithArgs)

1.2  構(gòu)造器中的this

  你可以通過new 將一個函數(shù)當做一個構(gòu)造器來使用。new 操作創(chuàng)建了一個新的對象,并將這個對象通過this 傳入構(gòu)造器中。

復制代碼 代碼如下:

var savedThis;
function Constr() {
    savedThis = this;
}
var inst = new Constr();
console.log(savedThis === inst); // true

JS中new 操作的實現(xiàn)原理大概如下面的代碼所示(更準確的實現(xiàn)請看這里,這個實現(xiàn)也比較復雜一些):

復制代碼 代碼如下:

function newOperator(Constr, arrayWithArgs) {
    var thisValue = Object.create(Constr.prototype);
    Constr.apply(thisValue, arrayWithArgs);
    return thisValue;
}

1.3  方法中的this

  在方法中this 的用法更傾向于傳統(tǒng)的面向?qū)ο笳Z言:this 指向的接收方,也就是包含有這個方法的對象。

復制代碼 代碼如下:

var obj = {
    method: function () {
        console.log(this === obj); // true
    }
}
obj.method();

2、作用域中的this

  在瀏覽器中,作用域就是全局作用域,this 指的就是這個全局對象(就像window):

復制代碼 代碼如下:

<script>
    console.log(this === window); // true
</script>

在Node.js中,你通常都是在module中執(zhí)行函數(shù)的。因此,頂級作用域是個很特別的模塊作用域(module scope):

復制代碼 代碼如下:

// `global` (not `window`) refers to global object:
console.log(Math === global.Math); // true

// `this` doesn't refer to the global object:
console.log(this !== global); // true
// `this` refers to a module's exports:
console.log(this === module.exports); // true

3、eval()中的this

  eval()可以被直接(通過調(diào)用這個函數(shù)名'eval')或者間接(通過別的方式調(diào)用,比如call())地調(diào)用。要了解更多細節(jié),請看這里。

復制代碼 代碼如下:

// Real functions
function sloppyFunc() {
    console.log(eval('this') === window); // true
}
sloppyFunc();

function strictFunc() {
    'use strict';
    console.log(eval('this') === undefined); // true
}
strictFunc();

// Constructors
var savedThis;
function Constr() {
    savedThis = eval('this');
}
var inst = new Constr();
console.log(savedThis === inst); // true

// Methods
var obj = {
    method: function () {
        console.log(eval('this') === obj); // true
    }
}
obj.method();

 4、與this有關(guān)的陷阱

  你要小心下面將介紹的3個和this 有關(guān)的陷阱。要注意,在下面的例子中,使用Strict模式(strict mode)都能提高代碼的安全性。由于在實函數(shù)中,this 的值是undefined,當出現(xiàn)問題的時候,你會得到警告。

  4.1  忘記使用new

  如果你不是使用new來調(diào)用構(gòu)造器,那其實你就是在使用一個實函數(shù)。因此this就不會是你預期的值。在Sloppy模式中,this 指向的就是window 而你將會創(chuàng)建全局變量:

復制代碼 代碼如下:

function Point(x, y) {
    this.x = x;
    this.y = y;
}
var p = Point(7, 5); // we forgot new!
console.log(p === undefined); // true

// Global variables have been created:
console.log(x); // 7
console.log(y); // 5

不過如果使用的是strict模式,那你還是會得到警告(this===undefined):

復制代碼 代碼如下:

function Point(x, y) {
    'use strict';
    this.x = x;
    this.y = y;
}
var p = Point(7, 5);
// TypeError: Cannot set property 'x' of undefined

4.2 不恰當?shù)厥褂梅椒?/P>

  如果你直接取得一個方法的值(不是調(diào)用它),你就是把這個方法當做函數(shù)在用。當你要將一個方法當做一個參數(shù)傳入一個函數(shù)或者一個調(diào)用方法中,你很可能會這么做。setTimeout()和注冊事件句柄(event handlers)就是這種情況。我將會使用callIt()方法來模擬這個場景:

復制代碼 代碼如下:

/** Similar to setTimeout() and setImmediate() */
function callIt(func) {
    func();
}

如果你是在Sloppy模式下將一個方法當做函數(shù)來調(diào)用,*this*指向的就是全局對象,所以之后創(chuàng)建的都會是全局的變量。

復制代碼 代碼如下:

var counter = {
    count: 0,
    // Sloppy-mode method
    inc: function () {
        this.count++;
    }
}
callIt(counter.inc);

// Didn't work:
console.log(counter.count); // 0

// Instead, a global variable has been created
// (NaN is result of applying ++ to undefined):
console.log(count);  // NaN

如果你是在Strict模式下這么做的話,this是undefined的,你還是得不到想要的結(jié)果,不過至少你會得到一句警告:

復制代碼 代碼如下:

var counter = {
    count: 0,
    // Strict-mode method
    inc: function () {
        'use strict';
        this.count++;
    }
}
callIt(counter.inc);

// TypeError: Cannot read property 'count' of undefined
console.log(counter.count);

要想得到預期的結(jié)果,可以使用bind():

復制代碼 代碼如下:

var counter = {
    count: 0,
    inc: function () {
        this.count++;
    }
}
callIt(counter.inc.bind(counter));
// It worked!
console.log(counter.count); // 1

bind()又創(chuàng)建了一個總是能將this的值設置為counter 的函數(shù)。

  4.3 隱藏this

  當你在方法中使用函數(shù)的時候,常常會忽略了函數(shù)是有自己的this 的。這個this 又有別于方法,因此你不能把這兩個this 混在一起使用。具體的請看下面這段代碼:

復制代碼 代碼如下:

var obj = {
    name: 'Jane',
    friends: [ 'Tarzan', 'Cheeta' ],
    loop: function () {
        'use strict';
        this.friends.forEach(
            function (friend) {
                console.log(this.name+' knows '+friend);
            }
        );
    }
};
obj.loop();
// TypeError: Cannot read property 'name' of undefined

上面的例子里函數(shù)中的this.name 不能使用,因為函數(shù)的this 的值是undefined,這和方法loop()中的this 不一樣。下面提供了三種思路來解決這個問題:

  1、that=this,將this 賦值到一個變量上,這樣就把this 顯性地表現(xiàn)出來了(除了that,self 也是個很常見的用于存放this的變量名),之后就使用那個變量:

復制代碼 代碼如下:

loop: function () {
    'use strict';
    var that = this;
    this.friends.forEach(function (friend) {
        console.log(that.name+' knows '+friend);
    });
}

2、bind()。使用bind()來創(chuàng)建一個函數(shù),這個函數(shù)的this 總是存有你想要傳遞的值(下面這個例子中,方法的this):

復制代碼 代碼如下:

loop: function () {
    'use strict';
    this.friends.forEach(function (friend) {
        console.log(this.name+' knows '+friend);
    }.bind(this));
}

3、用forEach的第二個參數(shù)。forEach的第二個參數(shù)會被傳入回調(diào)函數(shù)中,作為回調(diào)函數(shù)的this 來使用。

復制代碼 代碼如下:

loop: function () {
    'use strict';
    this.friends.forEach(function (friend) {
        console.log(this.name+' knows '+friend);
    }, this);
}

5、最佳實踐

理論上,我認為實函數(shù)并沒有屬于自己的this,而上述的解決方案也是按照這個思想的。ECMAScript 6是用箭頭函數(shù)(arrow function)來實現(xiàn)這個效果的,箭頭函數(shù)就是沒有自己的this 的函數(shù)。在這樣的函數(shù)中你可以隨便使用this,也不用擔心有沒有隱式的存在。

復制代碼 代碼如下:

loop: function () {
    'use strict';
    // The parameter of forEach() is an arrow function
    this.friends.forEach(friend => {
        // `this` is loop's `this`
        console.log(this.name+' knows '+friend);
    });
}

我不喜歡有些API把this 當做實函數(shù)的一個附加參數(shù):

復制代碼 代碼如下:

beforeEach(function () { 
    this.addMatchers({ 
        toBeInRange: function (start, end) { 
            ...
        } 
    }); 
});

把一個隱性參數(shù)寫成顯性地樣子傳入,代碼會顯得更好理解,而且這樣和箭頭函數(shù)的要求也很一致:

復制代碼 代碼如下:

beforeEach(api => {
    api.addMatchers({
        toBeInRange(start, end) {
            ...
        }
    });
});

相關(guān)文章

  • javascript斷點調(diào)試心得分享

    javascript斷點調(diào)試心得分享

    javascript中程序是怎么可以中斷執(zhí)行,然后一步一步走下去。而且debug的時候,可以看到變量,調(diào)用棧等東西。這個是如何實現(xiàn)的?
    2016-04-04
  • 檢測是否已安裝 .NET Framework 3.5的js腳本

    檢測是否已安裝 .NET Framework 3.5的js腳本

    管理員必須首先確認存在 .NET Framework 3.5 運行庫,然后才能將 Windows Presentation Foundation (WPF) 應用程序部署在面向 .NET Framework 3.5 的系統(tǒng)上。
    2009-02-02
  • js電話號碼驗證方法

    js電話號碼驗證方法

    JS電話號碼驗證是比較常的一種驗證,下邊給出一個JavaScript驗證電話號碼的小例子。國內(nèi)固定電話都是七位或8位的數(shù)字組成的,還可以帶有長途的區(qū)號。
    2015-09-09
  • 用JavaScript實現(xiàn)讓瀏覽器停止載入頁面的方法

    用JavaScript實現(xiàn)讓瀏覽器停止載入頁面的方法

    下面小編就為大家?guī)硪黄肑avaScript實現(xiàn)讓瀏覽器停止載入頁面的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • 常用的9個JavaScript圖表庫詳解

    常用的9個JavaScript圖表庫詳解

    本篇文章給詳細講解了9個JavaScript圖表庫以及用法,需要的朋友參考學習下。
    2017-12-12
  • 微信小程序去哪里找 小程序到底如何使用(附小程序名單)

    微信小程序去哪里找 小程序到底如何使用(附小程序名單)

    今天凌晨,微信負責人張小龍在微信朋友圈曬出了一組圖,網(wǎng)友看到紛紛“炸裂”,這到底是什么?是的,微信小程序如約上線,微信小程序怎么打開,微信小程序在哪里進入,請閱讀本文
    2017-01-01
  • js點擊文本框彈出可選擇的checkbox復選框

    js點擊文本框彈出可選擇的checkbox復選框

    這篇文章主要介紹了js點擊文本框彈出可選擇的checkbox復選框的相關(guān)資料,需要的朋友可以參考下
    2016-02-02
  • Javascript在IE和Firefox瀏覽器常見兼容性問題總結(jié)

    Javascript在IE和Firefox瀏覽器常見兼容性問題總結(jié)

    這篇文章主要介紹了Javascript在IE和Firefox瀏覽器常見兼容性問題,結(jié)合實例形式總結(jié)分析了javascript在IE與Firefox瀏覽器中常見的各種兼容性問題與相應的解決方法,需要的朋友可以參考下
    2016-08-08
  • 微信小程序 自定義消息提示框

    微信小程序 自定義消息提示框

    這篇文章主要介紹了微信小程序 自定義消息提示框的相關(guān)資料,wx.showToast(OBJECT)接口調(diào)用,實現(xiàn)改功能,需要的朋友可以參考下
    2017-08-08
  • javascript算法解數(shù)獨實現(xiàn)方案示例

    javascript算法解數(shù)獨實現(xiàn)方案示例

    這篇文章主要為大家介紹了javascript算法解數(shù)獨實現(xiàn)方案示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08

最新評論