如何创建jQuery的数组对象? [英] How does jQuery create Array-Objects?

查看:214
本文介绍了如何创建jQuery的数组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

起初我还以为这只是分配的obj [0],则obj [1],则obj [2]等,以返回之前的jQuery对象,而长度的手动的分配。不过没有关系,因为执行console.log记录的数组,而不是一个对象。

At first I thought it was just assigning obj[0], obj[1], obj[2], etc. to the jQuery object before returning it, and that the length is manually assigned. But no, since console.log logs an array and not an object.

我参加了一个快速浏览一下jQuery的来源,但因为我不熟悉它,我也不会轻易破解它。 jQuery.makeArray 杀出第一,但它原来是什么我要找的对面,你居然用它失去了对象的方法。

I took a quick look at the jQuery source but since I'm not familiar with it I didn't crack it easily. jQuery.makeArray popped first, but it turned out to be the opposite of what I'm looking for, you actually lose the object methods by using it.

我的第一个猜测是第一启动数组,然后从复制对象的所有的属性和方法吧。

My first guess is initiating the array first, and then copying all the properties and methods from the object to it.

有谁与jQuery的源$ C ​​$ C的经验有一个明确的答案呢?

Does anybody with the jQuery source code experience have a clear answer to this?

推荐答案

这是为创建一个新的功能,并分配一个新的数组作为它的原型一样简单。

It's as simple as creating a new function and assigning it a new array as its prototype.

function ArrayLike() {}
ArrayLike.prototype = [];

因此​​,例如:

So for example:

function ArrayLike() {}
ArrayLike.prototype = [];
ArrayLike.prototype.fromArray = function(arr) {
    for(var i = 0; i < arr.length; i++)
        this.push(arr[i]);
};
ArrayLike.prototype.foo = function() {
    console.log("foo", this);
};

var a = new ArrayLike();
a.fromArray([1, 2]);
console.log(a);
a.foo();

http://jsfiddle.net/Xeon06/fUgaf/

这篇关于如何创建jQuery的数组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆