javascript-objects - How to make "this" in nested function refer to parent object or what is the best practice to this problem?
问题描述
From example code below I'm trying to add a method inside an object where it generates new name based on object properties but "this" in this context is referring global object but not the parent one
It's ok using arrow function but the functions won't be hoisted and I need to express the function before using it. I prefer knowing what it does before seeing the code.
using arrow function expression it does work but is not hoisted using function declaration it doesn't work but is hoisted
Is there any best practice approach to this kind of problem?
const agent = {
firsName: "John",
lastName: "Depp",
born: 12/04/1987,
secretName: function() {
return newFirstName() + newLastName()
function newFirstName() {
// complex codes here
return "Agent " + this.firstName // for simplicity
}
function newLastName() {
// complex codes here
return "Agent " + this.LastName // for simplicity
}
},
};
console.log(agent.secretName()) // logs "Agent undefinedAgent undefined"
解决方案
这可能是由于您的函数的词法范围。您可以在此处和此处阅读有关它的更多信息。
因此,如果您将辅助函数上移一级,它可以解决问题:
const agent = {
firstName: 'John',
lastName: 'Depp',
born: 12 / 04 / 1987,
newFirstName: function () {
// complex codes here
return 'Agent ' + this.firstName; // for simplicity
},
newLastName: function () {
// complex codes here
return 'Agent ' + this.lastName; // for simplicity
},
secretName: function () {
return this.newFirstName() + this.newLastName();
},
};
console.log(agent.secretName()); // logs "Agent undefinedAgent undefined"
推荐阅读
- swift - 谁能告诉我为什么当我按下凸轮按钮时我的应用程序崩溃了
- rust - 如何在不调用其中一个函数的情况下链接 C 库?
- azure-web-app-service - 移动浏览器无法查看 Azure 网站
- c++ - 使用“typename Container::value_type”作为返回值时无法推断模板参数
- typescript - 推断 TypeScript 泛型类类型
- javascript - 无法读取未定义的属性“toLowerCase”-REACT-FIRESTORE
- c - 为无法重命名的程序编写一个 C/C++ 完全透明的包装器
- c# - Unity 实例化的对象总是引用同一个对象
- python - Python:让 Pydub 使用 OSError:[Errno 2] 没有这样的文件或目录和 OSError:[WinError 740] 错误
- python-3.x - 循环浏览带有硒问题的页码链接