作用域链和原型链描述javaScript访问变量和属性的顺序

一、作用域链

Javascript引擎在执行环境对象中访问作用域内的变量,查找的顺序叫做作用域链

1.作用域链示例:

 每次调用,regular_joe在作用域内都有定义

//在全局作用域里,设置regular_joe
var regular_joe = "I am here to save the day!";
//调用作用域:全局。作用域链中的最近匹配:全局的regular_joe
//logs 'I am here to save the day!'
console.log(regular_joe);
function supermax(){
  var regular_joe = 'regular_joe is assigned';
  //调用作用域:全局->supermax()。
  //作用域链中的最近匹配:在supermax()中定义的regular_joe
  //logs 'regular_joe is assigned'
  console.log(regular_joe);

  function prison () {
    //在javascript中,当变量被声明时,声明会被提升到它所在函数的顶部,
    //并被赋予undefined值
    var regular_joe;
    //调用作用域:全局->supermax()->person()。
    //作用域链中的最近匹配:在person()中定义的regular_joe
    console.log(regular_joe);
  }
  //执行person()函数, 'logs' 
  prison();
}
supermax();

 二、原型链

多个对象基于类和原型的比较

基于类的

//step 1: defined class
public class Prisoner {
  public int sentence = 4;
  public int probation = 2;
  public string name;
  public string id;
//step 2: defined class struct function
  public Prisoner( string name,string id) {
    this.name = name;
    this.id = id;
  }
}
//step 3  实例化对象
Personer firstPrisoner = new Prisoner("Joe","12A");
Personer SecondPrisoner = new Prisoner("Sam","2BC");

 基于原型的

//1.定义原型的对象
var proto = {
  sentence : 4,
  probation : 2
};
//2.定义对象的构造函数
var Prisoner = function(name, id){
  this.name = name;
  this.id = id;
};
//3.将构造函数关联到原型
Prisoner.prototype = proto;
//4.实例化对象
//使用 Object.create 的常见工厂模式是使用工厂函数来创建并返回最终的对象
//所有的工厂函数我们以make<object_name>的形式进行命名
var makePrisoner = function( name, id ) {
  var prisoner = Object.create( proto );
  prisoner.name = name;
  prisoner.id = id;
  return prisoner;
};

var firstPrisoner = makePrisoner( 'Joe', '12A' );
var secondPrisoner = makePrisoner( 'Sam', '2BC' );

 说明了javascript是如何使用原型来创建共享相同属性的对象

 

posted @ 2015-04-12 04:02  小丸子的笑  阅读(272)  评论(0编辑  收藏  举报