JavaScript 对象问题:使用对象名称获取对象的 属性 值

JavaScript Object Question: get the property value of an object using the object name

我想问一个关于对象的 javascript 属性的问题。 在下面的代码中,我有一个 javascript 对象。我想在函数“testFunction”中使用 属性“testName”。我发现“this.testName”在 javascript 对象中不起作用,但如果我执行类似“TestObject.testName”的操作,它会正常工作。所以一般来说,在对象的函数中获取像“TestObject.testName”这样的属性值是错误的吗?

const TestObject= {
    testName:"testValue",
    testFunction: ()=>{
        var result = TestObject.testName+ "result"; 
        return result ;
    }
} ```

使用this.testName代替TestObject.testName

您可以在此处阅读有关 this 的更多信息: https://www.w3schools.com/js/js_this.asp

@edit

抱歉,我没有注意到您使用了箭头功能。尝试改用常规函数。箭头函数正在改变 this 关键字的工作方式

const TestObject= {
    testName:"testValue",
    testFunction: function(){
        var result = this.testName+ "result"; 
        return result ;
    }
}

您可以在此处找到更多相关信息:

So in general, is it wrong to get the values of properties like "TestObject.testName" inside of the objects' functions?

不适用于像那个那样的单例对象,不,它完全没问题(您已经使用了 const,因此没有人可以将 TestObject 重新分配为其他对象)。也就是说,原因它不起作用是因为您使用了箭头函数,而不是传统函数或方法。如果您使用传统的函数或方法,this 就可以正常工作(但请继续阅读):

// Traditional function
const TestObject1 = {
    testName:"testValue",
    testFunction: function() {
        var result = this.testName+ "result"; 
        return result ;
    }
};

console.log(TestObject1.testFunction());

// Method
const TestObject2 = {
    testName:"testValue",
    testFunction() {
        var result = this.testName+ "result"; 
        return result ;
    }
};

console.log(TestObject2.testFunction());

我说过“它会很好地工作”,但只有在调用 testFunction 时将 this 设置为 TestObject 时才会如此。调用 testFunction 可能导致 this 设置不正确,请参阅 How to access the correct this inside a callback? 的答案以了解有关这些情况以及如何处理它们的详细信息。