简体   繁体   English

对象上的Javascript数组表示法

[英]Javascript array notation on object

I'd like to know how this works behind the scenes: https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/ 我想知道这是如何在幕后工作的: https//learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a -jquery对象/

How does JQuery set up foo[0] to execute the get function. JQuery如何设置foo[0]来执行get函数。 I had a look at the source code but all I found was this: 我看了一下源代码,但我找到的只是这个:

get: function( num ) {
    return num != null ?

        // Return just the one element from the set
        ( num < 0 ? this[ num + this.length ] : this[ num ] ) :

        // Return all the elements in a clean array
        slice.call( this );
},

How can I my own object so that accessing an array index calls a function like this? 我如何自己的对象,以便访问数组索引调用这样的函数?

I'd like to do the same thing: 我想做同样的事情:

myObj[0];

acts identically to 行为与...相同

myObj.get(0);

Looking a JQuery this must be possible as it doesn't just set this[0] = 'whatever' for each index manually, it executes the .get function somehow. 看JQuery这一定是可能的,因为它不仅手动为每个索引设置this[0] = 'whatever' ,它以某种方式执行.get函数。 Is there a way to say whenever an array lookup is made, to execute a function? 有没有办法说每当进行数组查找时,执行一个函数?

It's because in jQuery 0 is the key of the property in the object which holds the DOMElement. 这是因为在jQuery 0是包含DOMElement的对象中属性的键。 This means that you're actually accessing an object by key, not an array by index. 这意味着您实际上是按键访问对象,而不是按索引访问数组。 The get() method is just a wrapper for that accessor. get()方法只是该访问器的包装器。 Here's a working example: 这是一个有效的例子:

 var obj = { '0': 'hello!', get: function(key) { return this[key]; } }; console.log(obj[0]); console.log(obj.get(0)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

How does JQuery set up foo[0] to execute the get function JQuery如何设置foo [0]来执行get函数

It's the other way round. 反过来说。 get(0) simply calls [0] . get(0)只需调用[0]

jQuery creates an array-like stack of element objects, so it follows that, to extraxt one, you can use array syntax, eg [0] . jQuery创建了一个类似于数组的元素对象的堆栈,因此,对于extraxt,你可以使用数组语法,例如[0]

After realising the JQuery method would not work for me as I wanted to execute code on the call I found a solution using Proxy objects: 在意识到JQuery方法对我不起作用之后,因为我想在调用时执行代码,我找到了使用Proxy对象的解决方案:

var p = new Proxy(Obj, {
   get(target, name, receiver) {
    console.log(name);
    return name;
   }
});

p[0] will print 0 and allow executing code inside the function. p[0]将打印0并允许在函数内执行代码。 I'm not sure if this will work in all browsers but this is for a node project. 我不确定这是否适用于所有浏览器,但这适用于节点项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM