gpt4 book ai didi

javascript - 如何在以下场景中保留此关键字

转载 作者:行者123 更新时间:2023-11-28 16:03:21 25 4
gpt4 key购买 nike

我正在开发 Backbone 应用程序。我正在添加mousedown使用主干的事件调用 select功能。里面select我正在设置的功能timeout它调用另一个函数 selection 。在 selection我想要控制台的功能 currently clicked element使用console.log(this.el) 。然而,this.el未定义,因为 this 不引用我当前的模块。 如何保留此关键字以便在选择功能中使用它?

这是我的代码

    events: {
'mousedown': 'select',
'mouseup': 'deselect'
},


select: function () {
this.timeoutId = setTimeout(this.selection, 1000);
},

deselect: function () {
clearTimeout(this.timeoutId);
},

selection: function () {
console.log(this.el);
}

最佳答案

你可以这样解决:

select: function() {
var self = this;
this.timeoutId = setTimeout(function() {
self.selection();
}, 1000);
}

许多浏览器还支持 bind 函数,它将对象作为 this 绑定(bind)到函数

select: function() {
this.timeoutId = setTimeout(this.selection.bind(this), 1000);
}

关于javascript - 如何在以下场景中保留此关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16162304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com