Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用数组方括号访问插件原型函数_Javascript_Jquery - Fatal编程技术网

Javascript 使用数组方括号访问插件原型函数

Javascript 使用数组方括号访问插件原型函数,javascript,jquery,Javascript,Jquery,我对JS非常陌生,我刚刚学习了modal.JS的语法。基本上我有一个小困难,很多经典的JS插件都使用下面的框架代码作为插件: var Modal = function(element , options){ this.options = options this.$body = $(document.body) this.$element = $(element) this.isShown = null this.$backdrop = this

我对JS非常陌生,我刚刚学习了modal.JS的语法。基本上我有一个小困难,很多经典的JS插件都使用下面的框架代码作为插件:

var Modal = function(element , options){
    this.options = options
    this.$body = $(document.body)
    this.$element = $(element)
    this.isShown = null
    this.$backdrop = 
    this.scrollbarWidth = 0
  } 


  Modal.prototype.toggle = function (_relatedTarget) {
      // do something
  }

  Modal.prototype.show = function (_relatedTarget) {
      // do something
  }


var data = new Modal(somthing , radnom); 

                          // now if we assume that option is "show", 
                          //the show function in Modal will be executed 
                          // but my question is data is not an array, so how can we use 
                          // [] square brackets to access the properties of Modal/data ?? 
data[option](_relatedtarget); 
现在我的问题是关于访问插件的属性,请参见如何使用以下语法调用函数:

data[option](_relatedtarget); 

在代码中查看我的注释。如何使用
[]
访问数据的属性;它不是数组,对吗

[]
不仅仅适用于阵列

您也可以使用
[]
访问对象的属性

你可以用

  • data[“show”]
    访问
    show
    方法

  • 数据。显示与之相同的内容

[]
的一个优点是可以使用括号内的变量

var option = "show";
data[option](something); // call the `show` method on `data`

如果您知道要调用的方法,那么在代码中使用
会更好

data.show(something); // much quicker (to type), and prettier
JavaScript具有数组:

var anArray = [ 1, 2, 3, 4 ];
和关联阵列(也称为贴图):

这两种数据结构都可以通过
[]
访问:

anArray[3]                  // will get the element of the array in position 3
                            // (starting counting frrom 0).
anAssociativeArray['first'] // will get the element of the associative array with the
                            // key 'first'.
还可以通过
.key
符号访问关联数组:

anAssociativeArray.first    // will also get the property with key 'first'.
如果您知道要访问的密钥,可以使用
表示法,但如果您想动态选择哪个密钥,则需要使用
[]
表示法

var whichOptionToPick = 'somethingElse';
var value = anAssociativeArray[ whichOptionToPick ]; // will get the value "Other".

[]
是一个属性访问器操作符,就像
一样。在我看来,在JavaScript中把对象称为“关联数组”或“映射”是不合适的
var whichOptionToPick = 'somethingElse';
var value = anAssociativeArray[ whichOptionToPick ]; // will get the value "Other".