我想知道这在幕后是如何工作的:https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/
JQuery是如何设置foo[0]
来执行get
函数的。我查看了源代码,但我发现的是:
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 );
},
我怎样才能拥有自己的对象以便访问数组索引时调用这样的函数?
我想做同样的事情:
myObj[0];
行为相同
myObj.get(0);
从 JQuery 来看,这一定是可行的,因为它不只是手动为每个索引设置 this[0] = 'whatever'
,它还会以某种方式执行 .get 函数。有没有办法说每当进行数组查找时执行一个函数?
最佳答案
这是因为在 jQuery 中,0
是持有 DOMElement 的对象中属性的键。这意味着您实际上是通过键访问对象,而不是通过索引访问数组。 get()
方法只是该访问器的包装器。这是一个工作示例:
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>
关于对象上的 Javascript 数组表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38143975/