我有一个在另一个文件中定义的对象,我无法编辑该对象。 我需要调用其中定义的函数,但未设置为方法。 我的测试不起作用,因为我的范围内不存在 callMe。
// Example
function ObjectCreator()
{
this.name = "I am an object";
var callMe = function()
{
console.log("You did it");
}
this.DontCallMe = function()
{
console.log("You should not have called me");
callMe();
}
return this;
}
我的文件
// My attempt
var foo = new ObjectCreator();
foo.test = function()
{
// throws not defined error
callMe();
};
foo.test();
如何在不编辑原始文件以将其公开的情况下调用 callMe()?
最佳答案
这是不可能的。该函数将仅在构造函数或嵌套在其上的其他作用域内定义 - 这就是词法作用域的工作原理。
关于javascript - 需要调用一个已经失去作用域的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741782/