Javascript 访问在首次创建后已更改的外部变量

Javascript 访问在首次创建后已更改的外部变量,javascript,function,Javascript,Function,我知道我可以访问函数对象中的外部变量,但这是我一直坚持的 zero = function (one) { this.one = one; this.two = { three: { four: function() { one.test(); } } } } 很抱歉,命名代码不正确:(。 但这是测试用例 foo = { test: function()

我知道我可以访问函数对象中的外部变量,但这是我一直坚持的

zero = function (one) {
    this.one = one;
    this.two = {
        three: {
            four: function() {
                one.test();
            }
        }
    }
}
很抱歉,命名代码不正确:(。 但这是测试用例

foo = {
    test: function() {
        console.log('foo test');
    }
}
bar = new zero(foo);
bar.two.three.four(); // prints 'foo test'
foo2 = {
    test: function() {
        console.log('another foo test');
    }
};
bar.one = foo2;
bar.two.three.four(); // still prints 'foo test' instead of 'another foo test'
它看起来像是
four
保留了
one
的引用,因为它的创建不是
bar
中变量的引用。我不知道如何直接访问外部变量。感谢阅读我的问题。

使用

var zero = function (one) {
    var _this = this;
    this.one = one;
    this.two = {
        three: {
            four: function () {
                _this.one.test();
            }
        }
    };
};
而不是

one.test();
它使用闭包变量而不是公共可见的实例属性

执行此操作时:

this.one = foo2;
实际上,您所做的是覆盖公共可见属性。但是,这与名为
one
的函数参数不同,该参数在您创建的函数的范围内。
one
在您的代码中从未更改,因此从初始赋值i获取阀门是很自然的n构造函数。为对象指定属性并不意味着它们是相同的。如果在构造函数中执行此操作:

function Test()
{   var test = {};
    this.test = test;
    test = { a: 1 };
    console.log(this.test.a);
}

new Test; // undefined is logged
在新函数中使用
\u this
的原因是
this
的值仅在调用函数时设置,而不是在定义函数时设置。例如,以以下行为为例:

function Example()
{   var _this = this;
    this.test1 = { func: function () { return this; }
    this.test2 = { func: function () { return _this; }
}

var instance = new Example;
var randomFunction1 = instance.test1.func;
var randomFunction2 = instance.test2.func;

instance.test1.func(); // the instance.test1 object
instance.test2.func(); // the actual instance

randomFunction1(); // the global object (though this will be undefined in strict mode)
randomFunction2(); // still the instance
第一种方法是这样的,因为该方法的父对象是
instance.test1
,而不是
instance
。通过将当时的对象引用分配给一个变量,我们可以永久存储该引用,并随时引用它


注意:您可能需要使用
var
来声明您的变量-这可以防止隐含的全局变量,这可能会特别令人讨厌,而且在严格模式下不允许分配给未声明的变量。

感谢您的快速回答。我理解了问题所在。也感谢您提供的提示。只有一件事,我明白了n人们在他们的代码中使用
\u this
,这是JS中的某种编码模式吗?我也注意到有时他们使用双下划线。哇,我现在看到了。使用
\u this
你仍然可以跟踪对其父对象的引用,而不是函数本身。这看起来像是我将继续使用的一种很酷的模式。感谢heaps Qantas tho我更喜欢JetStar…@EugeneYu:不是函数,而是方法直接属性(并从中调用)的对象。