保护javascript中的全局引用
下面的javascript代码允许您访问全局对象(窗口/工作者) 是否有一种方法可以确保内部this总是引用外部的上下文 我知道我能行保护javascript中的全局引用,javascript,scopes,Javascript,Scopes,下面的javascript代码允许您访问全局对象(窗口/工作者) 是否有一种方法可以确保内部this总是引用外部的上下文 我知道我能行 (new function Outer(){ 'use strict'; console.log(this); /* The object */ (function(){ // This function could be a 3rd Party function console.log(this); /* undefi
(new function Outer(){
'use strict';
console.log(this); /* The object */
(function(){ // This function could be a 3rd Party function
console.log(this); /* undefined ? !!*/
})();
});
但这会导致这个未定义
编辑
我知道绑定,但是如果内部函数是嵌套的呢。比如说
(function(){
(function(){
(function(){
console.log(this);// undefined
})();
})();
}).bind(this)();
我想要的是:Outer{}而不是使用变量对Outer的引用:-您可以使用
新函数外部(){
"严格使用",;
console.log(this);
(function(){//此函数可以是第三方函数
console.log(this);//您可以使用闭包变量:
(new function Outer(){
'use strict';
console.log(this);
var me = this;
(function(){
console.log(me);
})();
})();
这个技巧只是将“outer”This
存储在一个变量中,您可以从内部函数(以及内部函数等等)访问该变量
在某些情况下,这可能很有用,因为您可以访问内部的this
(如果有上下文)和外部的this
(new function Outer(){
'use strict';
console.log(this); /* The object */
var _this = this;
(function(){ // This function could be a 3rd Party function
console.log(_this); /* The outer object */
})();
})();
如果内部函数嵌套了几层呢?我想你的意思是.bind(this)(
),但是+1用于做正确的事情。(你也可以使用.call(this)
,然后让它回到原来的工作状态:-)@另一种解决方案是在另一个变量中存储对外部this
的引用,比如var that=this
,然后使用that
引用外部this
变量。但是,这需要编辑内部函数的代码。@SeanVieira是的,我的意思是调用…:)很好,我知道这是从问题中的代码中得到的,但是最后一个尾随()
不应该在那里,因为外部
函数是用新的
调用的。你也可以去掉包装()
。只要新的外部函数({…})
就足够了。所以你不想要窗口
,但你也不想要未定义的
。我不想打断你,但这两个默认值将用于调用没有任何其他此
值指示符的函数。这就是为什么我问的原因,我想知道是否存在一个不具备这两个值的技巧。但是我我想我必须满足于未定义的
不,没有技巧。我不确定如果不是这两者中的任何一个,值会是什么。ECMAScript 6将有一个词法this
,但这在今天几乎没有用处,而且它只适用于具有新语法的函数。:D感谢提醒:-)
new function Outer(){
'use strict';
var self = this;
console.log(this);
(function(){ // This function could be a 3rd Party function
console.log(self); //<-- Now it will it the one from the outer scope
})();
};
(new function Outer(){
'use strict';
console.log(this);
var me = this;
(function(){
console.log(me);
})();
})();
(new function Outer(){
'use strict';
console.log(this); /* The object */
var _this = this;
(function(){ // This function could be a 3rd Party function
console.log(_this); /* The outer object */
})();
})();