2016-04-01 62 views
-1

我做從nodeschool.io的JavaScript的做法,我是給這個代碼:JavaScript編程作用域鏈實踐

var a = 1, b = 2, c = 3; 
 

 
(function firstFunction(){ 
 
\t var b = 5, c = 6; 
 

 
\t (function secondFunction(){ 
 
\t \t var b = 8; 
 

 
\t \t (function thirdFunction(){ 
 
\t \t \t var a = 7, c = 9; 
 

 
\t \t \t (function fourthFunction(){ 
 
\t \t \t \t var a = 1, c = 8; 
 

 
\t \t \t })(); 
 
\t \t })(); 
 
\t })(); 
 
})();

我不能夠訪問這裏面,所以我嘗試任何事情它是這樣的:

var a = 1, b = 2, c = 3; 
 

 
var start = (function firstFunction(){ 
 
\t var b = 5, c = 6; 
 

 
\t var secondFunction = (function secondFunction(){ 
 
\t \t var b = 8; 
 

 
\t \t (function thirdFunction(){ 
 
\t \t \t var a = 7, c = 9; 
 

 
\t \t \t (function fourthFunction(){ 
 
\t \t \t \t var a = 1, c = 8; 
 

 
\t \t \t })(); 
 
\t \t })(); 
 

 
\t \t return { 
 
\t \t \t secondFunction: secondFunction, 
 
\t \t \t printB: function() { 
 
\t \t \t \t return b; 
 
\t \t \t } 
 
\t \t } 
 

 
\t })(); 
 

 
\t return { 
 
\t \t printC: function() { 
 
\t \t \t return c; 
 
\t \t } 
 
\t } 
 

 
})(); 
 

 
console.log("a: " + a + ", b: " + start.secondFunction.printB() + ", c: " + start.printC());

我不知道我的方法是否正確,但我一直堅持這一整天。你會如何解決這個問題,爲什麼我的代碼不能進入secondFunction.printC?

+4

方法是什麼?你想解決什麼問題? – Barmar

+1

'secondFunction'不是從'start'返回的嗎? – guest271314

+0

也爲什麼所有立即調用的函數,如果你將它們設置爲變量? – Damon

回答

1

嘗試類似這樣的事情。

var a = 1, b = 2, c = 3; 

var start = (function firstFunction(){ 
    var b = 5, c = 6; 
    var obj = {}; 

    (function secondFunction(){ 
    var b = 8 
    obj.secondFunction = function(){ 
     return b; 
    }; 
    (function thirdFunction(){ 
     var a = 7, c = 9; 
     obj.thirdFunction = function(){ 
      return c; 
     }; 
     (function fourthFunction(){ 
      var a = 1, c = 8; 
      obj.fourthFunction = function(){ 
       return c; 
      }; 
     })(); 
    })(); 
    })(); 
    return obj 
})(); 

console.log (start.secondFunction()) 
+0

我實際上通過添加obj.firstFunction = function(){return c; };在第一個函數中,並且能夠使用console.log(「a:」+ a +「,b:」+ start.secondFunction()+「,c:」+ start.firstFunction())返回所有內容。你能解釋一下你是怎麼來的?我需要以不同的方式思考? –