鍍金池/ 問答/網(wǎng)絡安全  HTML/ setTimeout傳遞對象參數(shù)問題

setTimeout傳遞對象參數(shù)問題

使用vue,SelectItem是綁定的click事件的處理函數(shù),獲取當前點擊的事件對象e,然后傳到setTimeout里給doSomeThing去使用,但是doSomeThing拿到e后輸出的e.currentTarget卻是null。于是我在SelectItem里console.log了一下,在傳入定時器前,target1能夠輸出正確的currentTarget,但在定時器里面,target2輸出為null。如果我先在外面用一個變量保存e.currentTarget,然后在定時器里面輸出這個變量卻可以了。請問這是為什么?

SelectItem: function(e){
    e.stopPropagation();
    clearTimeout(this.timer);
    var _this = this;
    //var target = e.currentTarget;
    console.log("target1: ", e.currentTarget);
    //console.log("target1: ", target);
    this.timer = setTimeout(function(){
        console.log("target2: ", e.currentTarget);
        //console.log("target2: ", target);
        _this.someData = _this.doSomeThing(e);
    }, 300);
}

此外我試了兩種方法傳遞e,一種是在毫秒數(shù)后面寫參數(shù),即:

this.timer = setTimeout(function(){
    //_this.doSomeThing(e);
}, 300, e);

另一種是用一個函數(shù)把doSomeThing包起來,在setTimeout里調(diào)用這個函數(shù):

this.timer = setTimeout(function(){
    this.foo(e);
}, 300);

foo: function(e){
    this.doSomeThing(e);
}

兩種方法都不行。

回答
編輯回答
下墜

樓上兄弟回答基本上正確。

當你在的setTimeout里的函數(shù)執(zhí)行的時候已經(jīng)進入了下一個的事件循環(huán)“tick”中,e.currentTarget被置為了null。

2017年9月28日 09:54
編輯回答
尐飯團

要分清楚e和e.currentTarget的區(qū)別。

e是對象事件的屬性的引用,它有一個叫currentTarget的值,結構大概如下:

e = {
    currentTarget: "A"
}

你把e傳到函數(shù)里,相當于把引用傳進去,但是e.currentTarget在后面時刻是會被重置的。過程和下面類似

var newE = e
console.log(newE.currentTarget)//有值
e.currentTarget = null // 重置,引用指向改變,但不會改變原來e.currentTarget指向的對像的值
console.log(newE.currentTarget)//null

而你直接保存e.currentTarget當然是有值的。

2017年10月24日 10:19