2015-04-07 47 views
0

嘿家伙我很新的JS和我只是经历了modal.js的语法,基本上我有一个小难度,很多经典的js插件使用下面的骨架该插件代码:访问插件原型函数使用数组square [] brakets

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); 

看到我的代码中的注释。我们如何使用[]访问数据的属性,它不是一个数组吗?

谢谢。

Alex-Z。

+0

'[]'是一个属性存取操作符,就像'.'。 – Xufox

回答

1

[]不只是阵列

可以使用[]在对象上访问属性了。

您可以使用

  • data["show"]访问show方法

OR

  • data.show这是同样的事情

一个优势[]的是,你可以在括号

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

如果你知道使用.你要调用该方法,更漂亮看在代码中使用的变量

data.show(something); // much quicker (to type), and prettier 
+0

我不会[这个东西](http://i.imgur.com/lyjRXD3.png)起来。人们实际上在互联网上向[我](https://github.com/naomik)这样谈话。 – naomik

1

JavaScript有数组:

var anArray = [ 1, 2, 3, 4 ]; 

和关联数组(也称为映射):

var anAssociativeArray = { first: "No. 1", second: 2, somethingElse: "Other" }; 

这些数据结构的两个可以通过[]进行访问:

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". 
+0

imo,我认为它不适合在JavaScript中调用对象“关联数组”或“地图” – naomik