1. 程式人生 > 實用技巧 >記一次使用js中的this關鍵字在ajax中使用,因傳入的this物件不同而引起的問題。

記一次使用js中的this關鍵字在ajax中使用,因傳入的this物件不同而引起的問題。

背景:

  在一次web網站開發維護中,使用手機驗證碼進行登入。再點選獲取手機驗證碼時,驗證碼按鈕並沒有置灰,同時也沒有出現倒數讀秒的效果。

設定按鈕倒數60秒前端程式碼:

 var clock = '';
    var nums = 60;
    var btn;
    function sendCode(thisBtn) {
        btn = thisBtn;
        btn.disabled = true; //將按鈕置為不可點選
        btn.value = nums + '秒重新獲取';
        btn.className = 'regGetcodeBtn1
'; if (clickNumber == 0) { clock = setInterval(doLoop, 1000); //一秒執行一次 } }
function doLoop() {
        nums--;
        if (nums > 0) {
            btn.value = nums + '秒後重新獲取';
            clickNumber = 1;
        } else {
            clearInterval(clock); //清除js定時器
            btn.disabled = false
; btn.value = '獲取驗證碼'; btn.className = 'regGetcodeBtn1 color'; nums = 60; //重置時間 clickNumber = 0; } }

在向後端請求獲取簡訊驗證碼成功之後,呼叫sendCode()函式,實現如下效果:

但是在ajax請求,呼叫時,實際上該效果並沒有出現,程式碼如下:

$.ajax({
            url: servletUrl,
            type: "post",
            dataType: 'JSON',
            data: { name: name, securityCode: txtsecurityCode1/* strTelphone: strCodeTelphone, securityCode: txtsecurityCode1*/},
            success: function (result) {
                //已經存在該名字提示使用者
                if (result.status == false) {
                    console.log("傳入ajax中的this物件:" + this.location);
                    $('#hdVerifCode').val(0);
                    nums = 0;
                    layer.alert(result.msg, { icon: 2 });
                    layer.close(loadingindex);
                    // 重新整理驗證碼
                    $('#secImg').click();
                } else {
                    $('#hdVerifCode').val(1);
                    sendCode(this
)
; } },

 這個時候,我i傳入一個this,原本意是代替觸發的btn物件,但是實際上,在傳入sendCode中時,卻並不是我所想的。查閱資料,學習了一下js中this這個關鍵字,好吧,在ajax的success中,this代替了傳入到看ajax的bbjcet物件,而不是觸發按鈕事件的btn了。所以,並沒有改變按鈕物件的狀態。

解決辦法:

  A。在呼叫ajax方法之前,定義一個物件,接受this指代的物件。var that=this;然後在sendCode(that)傳入包裝好的this物件即可。

  B。使用bind(this)關鍵字,綁定當前的this的事件物件。

總結 this關鍵字:

  1。全域性作用域和普通函式中,指向全域性物件window;

console.log(this) //window

//function宣告函式
function bar () {console.log(this)}
bar() //window

//function宣告函式賦給變數
var bar = function () {console.log(this)}
bar() //window

//自執行函式
(function () {console.log(this)})(); //window

 2。方法呼叫中,誰呼叫方法,this指向誰

//物件方法呼叫
var person = {
  run: function () {console.log(this)}
}
person.run() // person

//事件繫結
var btn = document.querySelector("button")
btn.onclick = function () {
  console.log(this) // btn
}
//事件監聽
var btn = document.querySelector("button")
btn.addEventListener('click', function () {
  console.log(this) //btn
})
//jqery中的ajax
$.ajax(object)
在ajax的succes中,this指向了傳入ajax的物件obj
success:function(){
            $(this).prevAll('p').css("text-decoration","line-through");
      }.bind(this)//使用bind(this)綁定當前this事件

3.在建構函式和建構函式原型中,this指向建構函式的例項。

//不使用new指向window
function Person(name) {
  console.log(this) // window
  this.name = name;
}
Person('inwe')
//使用new
var people = new Person('iwen')
function Person(name) {
  this.name = name
  console.log(this) //people
  self = this
}
console.log(self === people) //true
//這裡new改變了this指向,將this由window指向Person的例項物件people

4. 箭頭函式中指向外層作用域的 this