gpt4 book ai didi

javascript - this.property 在 nodejs 中返回 undefined

转载 作者:行者123 更新时间:2023-11-30 17:36:54 25 4
gpt4 key购买 nike

我在 node 中编写应用程序时遇到了一些奇怪的事情。

我使用 call() 方法将对象传递给函数以修改该对象。当我在函数内部执行 console.log(this) 时,它返回对象正常,但是当我尝试执行 console.log(this.foo) 或尝试修改对象时,它说未定义。 更新:我还必须提到我在一个对象中传递了这个函数,因为我必须将这些函数注入(inject)到另一个函数中。 (更具体地说,我正在尝试让 this 工作。也许这也是问题的一部分。

var obj = {name: "John", age: 23};
var functions = {up: function() { /* do stuff */ }, down: function() { /* do stuff */
functions.up.call(obj);

up: function() {
console.log(this); //returns {name: "John", age: 23}
console.log(this.name); //returns undefined
this.wife = "Jenny"; //doesn't do anything
}

但是,如果我使用“_”设置属性,它们确实存在,但在我调用 console.log(this) 时不会显示;

up: function() {
this._wife = "Jenny"; //doesn't do anything
console.log(this._wife); //returns "Jenny"
console.log(this); //still returns {name: "John", age: 23}
}

我已经尝试了一切,例如使用 this.set(key, value)、this.get(key)、this.attributes["name"].value,..

也许我误解了“this”的工作原理,但经过数小时的搜索和尝试后,我一无所知..

最佳答案

在控制台中尝试您的代码时,我将语法固定为一个函数表达式,它对我有用,也许这是您的问题?

var obj = {name: "John", age: 23};
up.call(obj);

function up() {
console.log(this); //returns {name: "John", age: 23}
console.log(this.name); //returns "John"
this.wife = "Jenny"; // works
console.log(this);
}

关于javascript - this.property 在 nodejs 中返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855565/

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