gpt4 book ai didi

javascript - Javascript对象在构造过程中可以调用自己的方法吗?

转载 作者:行者123 更新时间:2023-11-30 10:58:46 24 4
gpt4 key购买 nike

我有以下 JS,与 Undum 交互交互式小说库:

undum.game.situations = {
main: new undum.SimpleSituation(
"",
{
enter: function(character, system, from) {
...
},
actions: {
testMethod: function() {
return "hello from test method";
},
'test-action': function(character, system, action) {
console.log("testMethod for main situation says: "+this.testMethod());
...
}
}
}
),
...other situation defs
}

当我进入 actions 的 test-action 方法时,控制台显示错误“Uncaught TypeError: this.testMethod is not a function”。

我猜这个问题与 testMethod 及其调用者被定义为 SimpleSituation 构造函数的一部分有关?如果是这样,我应该如何设置像这样的基于事件的代码,其中一个对象需要在构造过程中 Hook 到它自己的方法(尽管它们实际上并没有在构造过程中被调用)?

A fiddle使用一些类似的样板,我认为演示相同的分类行为工作正常:

function Obj(optionsObj) {
optionsObj.testMethod();
}
var myObj = new Obj(
{
testMethod: function() {
alert("hello from test method");
}
}
)

最佳答案

理解这个问题的关键是,在 JS 关键字中,这完全是关于调用上下文而不是被调用上下文——我读过 W3 schools blurb关于关键字this,但它有点误导。在他们的示例代码中

var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

他们将 fullName 称为 person 的方法,其中关键字 this 将引用封闭对象。然而,只有当 fullName 的调用上下文是在 person 的实例上时,这才是正确的,例如

var p = new person();
p.fullName();

在 person 的实例上被调用是使 fullName 成为方法的原因。然而,就其本身而言,fullName 只是一个与任何其他函数一样的函数,并且可以从 person 中提取并用作独立函数:

var fullNameFn = person.fullName;
fullNameFn(); // in this case, keyword this points to global object (usually Window) or undefined in strict mode.

我在Undum看的情况竟然是这样的情况。它没有调用 main.actions.test-action(),而是执行以下操作以响应玩家单击操作链接:

SimpleSituation.prototype.act = function(character, system, action) {
// my take-action action function is extracted and stored as response
var response = this.actions[action];
try {
response(character, system, action);
} catch (err) {
if (response) system.write(response);
}
if (this._act) this._act(character, system, action);
};

实际的测试操作函数是从 Situation 实例中提取并独立执行的,导致关键字 this 指向 Window。

关于javascript - Javascript对象在构造过程中可以调用自己的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886009/

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