Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom array object

I'm new to prototyping and instantiations and therefore had a question :

  • How can I create a function that constructs a new array that also has some properties added with prototype but without modifying the default Array function ?

For example :

function Cool_Object() {
    this = new Array() // Construct new array.
    //This is only for the example. I know you can't do that.
}
Cool_Object.prototype.my_method = function() {
    // Some method added
};

So, if you call :

var myObject = new Cool_Object();

myObject would be an array and have a method called "my_method" (which actually calls a function).

But the default Array object would be intact.

Thanks in advance !

like image 818
m_vdbeek Avatar asked Jan 11 '13 00:01

m_vdbeek


1 Answers

You've got it a bit backwards. Just use Array.prototype as your custom object's prototype.

function Cool_Object() {

    this.my_method = function () {
        return 42;
    }
}

Cool_Object.prototype = Array.prototype;

var foo = new Cool_Object();
foo.my_method(); // 42
foo.push(13);
foo[0]; // 13

You can get both Array.prototype and my_method on Cool_Object's prototype, without modifying Array.prototype, by introducing an intermediate type:

function Even_Cooler() {}
Even_Cooler.prototype = Array.prototype;

function Cool_Object() {}
Cool_Object.prototype = new Even_Cooler();

Cool_Object.prototype.my_method = function () {
    return 42;
}
like image 172
Matt Ball Avatar answered Oct 25 '22 17:10

Matt Ball