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

kognpnkq  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(111)

我有一个目标:

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':[]
  }
}

所以我想把屏幕大小存储在一个变量中,当用户改变窗口大小时,这个变量也随之改变。
问题是在re-size事件函数中,我必须输入“long_object_name”来“到达”properties”对象,所以我的问题是,是否有其他方法可以“到达”properties”对象,例如this.properties,但this在这种情况下不起作用,对吗?

nfs0ujit

nfs0ujit1#

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':[]
  }
}
0ejtzxu1

0ejtzxu12#

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':[]
  }
}

相关问题