Javascripting范围链实践

时间:2016-04-01 02:20:47

标签: javascript

我正在从nodeschool.io做javascript实践,我得到了这段代码:



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

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

	(function secondFunction(){
		var b = 8;

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

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

			})();
		})();
	})();
})();




我无法访问其中的任何内容,所以我尝试了这样:



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

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

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

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

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

			})();
		})();

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

	})();

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

})();

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




我不知道我的方法是否正确,但我整天坚持这一点。您将如何处理此问题以及为什么我的代码无法进入secondFunction.printC?

1 个答案:

答案 0 :(得分: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() )