最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

namespaces - JavaScript closures and name clobbering - Stack Overflow

programmeradmin2浏览0评论

Are variables defined inside an inner function that have the same name as a variable in an outer function isolated from the outer variable?

function() {
    var myTest = "hi there";
    ( function( myTest ) {
        myTest = "goodbye!";
    } )();
    console.log( myTest ); // myTest should still be "hi there" here, correct?
}

Naturally if I didn't declare myTest inside the inner function it would create a closure and modify the original. I just want to make sure that variables declared within an inner function are always isolated to that function even if their name may conflict with an outer scope.

Are variables defined inside an inner function that have the same name as a variable in an outer function isolated from the outer variable?

function() {
    var myTest = "hi there";
    ( function( myTest ) {
        myTest = "goodbye!";
    } )();
    console.log( myTest ); // myTest should still be "hi there" here, correct?
}

Naturally if I didn't declare myTest inside the inner function it would create a closure and modify the original. I just want to make sure that variables declared within an inner function are always isolated to that function even if their name may conflict with an outer scope.

Share Improve this question asked Mar 8, 2012 at 16:11 devios1devios1 38k48 gold badges167 silver badges268 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 12

Yes, they effectively do. Each function creates a new scope, and the closest scope in which a requested variable is declared always takes precedence. No exceptions.

Just for the sake of pleteness. In these very similar examples, here is what happens with no parameter

var x = 'a';
( function(  ) {   //note that there is no parameter here
    x = 'b';
    alert('inner:'+x); //b
} )();
alert('outer:'+x); //b

and a var with the same name

var x = 'a';
( function(  ) {
    var x = 'b';
    alert('inner:'+x); //b
} )();
alert('outer:'+x); //a
发布评论

评论列表(0)

  1. 暂无评论