gpt4 book ai didi

javascript - 将 "this"设置为实例,在创建原型(prototype)函数期间设置的回调中

转载 作者:行者123 更新时间:2023-11-30 00:24:03 25 4
gpt4 key购买 nike

我有这个代码:

var createAllAreSelectedClickedHandler = function(selectablesArrayGetter) {
return function() {
var array = selectablesArrayGetter();
var desiredState = array.every(function(selectable) { return selectable.selected; }) ? false : true;
array.forEach(function(selectable) {
selectable.selected = desiredState;
});
};
};

接着是这个:

function PromoViewModel() { this.registrations = [...] }   

PromoViewModel.prototype.allEventsSelectedClickedHandler = createAllAreSelectedClickedHandler(function() { return this.registrations; }));

我无法设置正确的值。创建函数时的“this”值指向 Window,所以我不能执行 .bind(this)。我试过 .bind(PromoViewModel.prototype) 但它缺少在构造函数中设置的所有宝贵实例字段。

我知道我可以简单地在构造函数中设置 this.allEventsSelectedClickedHandler,但我试图将方法创建与变量分开。

最佳答案

问题是 selectablesArrayGetter(); 调用决定了 this value用于回调。

您将需要使用 call“传递”调用方法(即您返回的闭包)的 this 值:

var array = selectablesArrayGetter.call(this);

关于javascript - 将 "this"设置为实例,在创建原型(prototype)函数期间设置的回调中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32079025/

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