对象Heirarchy中的可变范围

时间:2015-09-24 07:24:58

标签: javascript scope global-variables

我正在经历' You Dont Know Javascript'系列(真棒btw)。通过'范围'章节&它的building metaphor' ,不应该运行以下Js代码,因为一个obj在其父对象的范围内?

var aaa = {  // global obj
  a : 'a',
  bbb : { // child obj
    b : 'b',
    ccc : {  // child's child obj
      c : 'c',
      dfunc : function () {
        console.log (a);
        console.log (b);
        console.log (c);
      }
    }
  }
}

aaa.bbb.ccc.dfunc(); // ReferenceError: a is not defined

运行后,我收到上述评论错误。

2 个答案:

答案 0 :(得分:1)

ReferenceError:a未定义为正确

在您的代码中只定义aaa,其他所有内容都是aaa对象的属性

var aaa = {  // global obj
  a : 'a',
  bbb : { // child obj
    b : 'b',
    ccc : {  // child's child obj
      c : 'c',
      dfunc : function () {
        console.log (a); // its a property  of aaa 
        console.log (b);
        console.log (c);
      }
    }
  }
}

答案 1 :(得分:1)

您可以使用原型继承..

以下内容相同,但Object.create()通过原型树继承了它所创建对象的属性。

var aaa = {};
var bbb = Object.create(aaa); // create with the properties of aaa
var ccc = Object.create(bbb); // create with the properties of bbb

aaa.a = "a1";  // add new properties to all
bbb.b = "b2";
ccc.c = "c3";

// not needed but 
aaa.bbb = bbb;  // just to be the same reference bbb in aaa
bbb.ccc = ccc;  // and ccc in bbb

aaa.saySomething = function(){  // add the function to the base object
    console.log(this.a);
    console.log(this.b);
    console.log(this.c);
}
// call from the top gets all properties
ccc.saySomething(); // outputs a1 b2 c3

// call from the middle
bbb.saySomething(); // outputs a1 b2 undefined 
                    // this does not have access to ccc

// call from the bottom
aaa.saySomething(); // outputs a1 undefined undefined 
                    // this doe not have access to bbb and ccc