Javascript:重新分配'这',或替代方案

Javascript: Reassigning 'this', or alternative?

本文关键字:方案 分配 Javascript 新分配      更新时间:2023-09-26

我正在构建一个小型应用程序,它是销售查询过程的一部分。它有"页面"供访问者浏览。我已经将这些页面作为一个大对象文字的一部分进行了布局。在下面的代码中,branch-select就是其中一个页面。如您所见,init()函数通过使用this引用parent branch-select来设置同级值。然而,save()函数是从点击事件中调用的,所以我似乎每次都要费力地写出完整的对象引用来设置值,而不是使用this?请参阅代码&下面的评论说明了这个问题:

    // This is part of a larger object called "stepData"
        "previous page": {
            // ...
        }
        "branch-select": {
            ref: "Select Type",
            visited: false, 
            init: function(){
                this.visited = true;  // Here I can use "this" to set other values in the parent object
                // ....
            },
            next: "",
            save: function(){
                branchKey = $(this).attr('data-value');   // this function is invoked from a click event, so "this" refers to the DOM element that was clicked. Therefore throughout the rest of the function if I want to set values on the parent object, I have to write out the full object reference each time...
                switch(branchKey){
                    case "Lodges":
                        stepData['branch-select'].ref = "Lodges";
                        stepData['branch-select'].values[0].a = "Lodges";
                        stepData['branch-select'].next = "lodge-2";     // Do I really have to write out stepData['branch-select'] each time?
                        break;
                    case "Caravans":
                        stepData['branch-select'].ref = "Caravans";
                        stepData['branch-select'].values[0].a = "Caravans";
                        stepData['branch-select'].next = "van-2";
                        break;
                }
                stepData[stepData['branch-select'].next].init();
            }
        },
        "next page": {
            // ...
        }

为了DRY(不要重复)代码的利益,我想知道是否有任何巧妙的解决方案?

编辑:

Webkit的回答提出了一个新问题;点击的DOM元素(.branchselect)是动态引入的,所以要绑定点击事件,我必须使用:

    $("#template-holder").on('click', ".branch-select", stepData['branch-select'].save);

(模板持有者是始终存在的父元素)。如何将call()方法集成到上面的代码中?

在处理事件时让"this"引用对象的另一种方法是使用"call"。

例如:

var setData = {
    save: function(){
        // 'this' shall be setData!
        var _bs = this['branch-select'];
        _bs.ref = "Lodges"...
    }
}

然后:

$(".someElement").on('click', function() {
    setData.save.call(setData)
});

**更新(我很确定这应该同样有效):

$("#template-holder").on('click', ".branch-select", function() {
    stepData['branch-select'].save.call(setData)
});