在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

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

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);

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

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

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

兩種方法都不行。

回答
編輯回答
下墜

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

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

2017年9月28日 09:54
編輯回答
尐飯團(tuán)

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

e是對象事件的屬性的引用,它有一個(gè)叫currentTarget的值,結(jié)構(gòu)大概如下:

e = {
    currentTarget: "A"
}

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

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

而你直接保存e.currentTarget當(dāng)然是有值的。

2017年10月24日 10:19