那么您的问题接缝是当 setTimeout 计时器运行时this
调用您的函数的函数将不一样,因此如果您想要正确的行为,您需要更改它:this
window
从这里获取覆盖 setTimeout 和 setInterval 全局与此覆盖:
// Just place this lines in your javascript file
// Enable the passage of the 'this' object through the JavaScript timers
var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeST__(vCallback instanceof Function ? function () {
vCallback.apply(oThis, aArgs);
} : vCallback, nDelay);
};
window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
return __nativeSI__(vCallback instanceof Function ? function () {
vCallback.apply(oThis, aArgs);
} : vCallback, nDelay);
};
然后您的功能将按预期工作:
...
console.log(this.event.dataTransfer);
## DataTransferItemList {0: DataTransferItem, length: 1, item: function, clear: function, add: function}
setTimeout((function() {
return console.log(this.event.dataTransfer);
## DataTransferItemList {length: 0, item: function, clear: function, add: function}
}), 100);
...
希望能帮助到你