gpt4 book ai didi

javascript - 访问匿名函数中的对象值

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

我有一个对象(事物),它跟踪某些值以及一组条件:

var Thing = function(currentValue) {
this.currentValue = currentValue;
this.conditions = [];
};

可以将条件添加到此列表中:

Thing.prototype.addCondition = function(condition) {
this.conditions.push(condition);
}

我希望条件采取某种函数的形式,这样我就可以做到

thing.addCondition(thing.exampleCondition(valueToCheckFor));

这些条件都可以通过

检查
Thing.prototype.evaluateConditions = function() {
this.conditions.forEach(function(condition) {
if (condition()) {
//Do something
}
});
};

目前我有一个这样的条件函数:

Thing.prototype.exampleCondition = function(value) {
return function() {
return this.currentValue === value;
};
};

这显然不起作用 - this.currentValue 在匿名函数中未定义。我的问题是,我需要在调用评估条件()时根据 currentValue 的值评估传递到 exampleCondition 的值 - 因此我不能这样做

Thing.prototype.exampleCondition = function(value) {
var c = this.currentValue;
return function() {
return c === value;
};
};

我是一个 javascript 菜鸟,但希望你们这些聪明的人能在这里为我指明正确的方向。

最佳答案

在 JavaScript 中,每个函数始终根据上下文进行评估,上下文定义了 this 的值。

函数的上下文可以在调用函数时显式或隐式设置。要隐式设置上下文,您必须调用如下函数:

//z will be the context, in other words, inside method: this = z
a.b.c.d...z.method();

要显式设置上下文,您可以使用 Function 对象的原型(prototype)中的两个函数: apply and call 。这两个与每个浏览器兼容,因此您不会遇到问题。问题是,使用这两个函数,您每次调用函数时都会设置上下文,因此如果直接使用它们,它不会帮助您解决问题。

您必须定义一个函数,该函数每次调用时始终根据相同的上下文进行计算。为此,您可以使用函数对象原型(prototype)中定义的绑定(bind)函数,问题是它与旧浏览器不兼容,因为它是 ECMA-262 第 5 版的最新添加内容。不过,解决方案可以将每个条件函数绑定(bind)到 addCondition 函数中的对象:

Thing.prototype.exampleCondition = function(value) {
return function() {
return this.currentValue === value;
};
};

Thing.prototype.addCondition = function(condition) {
//The bind function will return a function that will always execute with your object as context
this.conditions.push(condition.bind(this));
}

对于浏览器兼容性,您可以 try this code 。将其放在脚本的开头,您可以确定您将拥有适用于每个浏览器的绑定(bind)功能。

另一种可能的解决方案是:

Thing.prototype.exampleCondition = function(value) {
var self = this;
return function() {
return self.currentValue === value;
};
};

问题是,在这种情况下,您没有使用上下文,您在返回的函数中忽略了它。您不使用上下文,而是将其替换为范围中定义的某些变量。为此,您将强制定义为条件函数的每个函数执行该小技巧。我认为第一种解决方案更好。

关于javascript - 访问匿名函数中的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25476929/

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