在全局范围内轻松访问函数中的类变量

时间:2012-03-17 20:04:27

标签: javascript javascript-events

我有一个对象

var long_object_name = {
  'init':function(){

    this.properties.the_screen_size[0] = window.innerWidth;
    this.properties.the_screen_size[1] = window.innerHeight;

    window.addEventListener('resize', function(){
      long_object_name.properties.the_screen_size[0] = window.innerWidth;
      long_object_name.properties.the_screen_size[1] = window.innerHeight;
    }, false);
  },
  'properties':{
    'the_screen_size':[]
  }
}

所以我想将屏幕大小存储在一个变量中,当用户更改窗口大小时,该变量会发生变化 问题是在重新调整大小事件函数中我要键入“long_object_name”以“到达”“属性”对象。所以我的问题是,有没有办法以另一种方式“到达”“属性”对象,例如“this.properties”,但“this”在这种情况下不起作用,对吧?

2 个答案:

答案 0 :(得分:1)

var long_object_name = {
  'init':function(){

    var screenSize = this.properties.the_screen_size;

    screenSize[0] = window.innerWidth;
    screenSize[1] = window.innerHeight;

    window.addEventListener('resize', function(){
      screenSize[0] = window.innerWidth;
      screenSize[1] = window.innerHeight;
    }, false);
  },
  'properties':{
    'the_screen_size':[]
  }
}

答案 1 :(得分:1)

var long_object_name = {
  'init':function(){

    var ss = this.properties.the_screen_size;

    ss[0] = window.innerWidth;
    ss[1] = window.innerHeight;

    window.addEventListener('resize', function(){
      ss[0] = window.innerWidth;
      ss[1] = window.innerHeight;
    }, false);
  },
  'properties':{
    'the_screen_size':[]
  }
}