首页 > 技术文章 > 作用域链 Scope Chain

lcw5945 2015-01-07 10:50 原文

Object.prototype.x = 10;
 
var w = 20;
var y = 30;
 

//console.log(x); // 10
 
(function foo() {
  var w = 40;
  var x = 100;

  with ({z: 50}) {
    console.log(w, x, y , z); // 40, 10, 30, 50
  }

  console.log(this.x, this.w); // 10, 20

  console.log(window.w); // 20
 
})();

  

Object.prototype.x = 10;
 
var w = 20;
var y = 30;
 

//console.log(x); // 10
 
(function foo() {
  var w = 40;
  var x = 100;

  with ({z: 50}) {
    console.log(this.w, this.x, this.y , z); // 20, 10, 30, 50
  }

  console.log(x, w); // 100, 40

  console.log(window.w); // 20
 
})();

  

在搜索__parent__ 之前先搜说 __proto__

 

闭包函数

Object.prototype.x = 10;
 
var w = 20;
var y = 30;
 

//console.log(x); // 10
 
(function foo() {
  var w = 40;
  var x = 100;
  
  (function(){
   console.log(w, x, y); //40,100,30
})();

 
})();

 

因为with会在运行期间产生临时的作用域,而闭包函数还是在foo的作用域内。

原文:http://www.nowamagic.net/librarys/veda/detail/1645

推荐阅读