tags:

views:

38

answers:

1

I found this piece of code which seems pretty cool. I see return new Set(array); written so i know set is a class. But what does Set[proto] mean and what does [push] mean and .pop and why is one a dot while the other is in square brace.

Also arguments[length] looks pretty cool. I imagine its an implicit parameter in each func? i am not sure how length works in this case. This looks really cool and i am very much a newbie at JS.

// Set
var Set = function (items) {
    this.items = [];
    this[length] = 0;
    this.type = "set";
    if (items) {
        for (var i = 0, ii = items[length]; i < ii; i++) {
            if (items[i] && (items[i].constructor == Element || items[i].constructor == Set)) {
                this[this.items[length]] = this.items[this.items[length]] = items[i];
                this[length]++;
            }
        }
    }
};
Set[proto][push] = function () {
    var item,
        len;
    for (var i = 0, ii = arguments[length]; i < ii; i++) {
        item = arguments[i];
        if (item && (item.constructor == Element || item.constructor == Set)) {
            len = this.items[length];
            this[len] = this.items[len] = item;
            this[length]++;
        }
    }
    return this;
};
Set[proto].pop = function () {
    delete this[this[length]--];
    return this.items.pop();
};
+3  A: 

In that code the proto variable is set to the string "prototype", and the push variable is set to "push". So, Set[proto] is the same as saying Set.prototype.

So this:

Set[proto][push] 

is the same as:

Set.prototype.push

The code is actually creating a function on the Set's prototype called push. A functions prototype is an object that all instances constructed from that function inherit.

For more information about prototype property read this

Matthew Manela