Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate JavaScript functions with custom prototypes

I use the following function to create instances of functions in JavaScript from an array of arguments:

var instantiate = function (instantiate) {
    return function (constructor, args, prototype) {
        "use strict";

        if (prototype) {
            var proto = constructor.prototype;
            constructor.prototype = prototype;
        }

        var instance = instantiate(constructor, args);
        if (proto) constructor.prototype = proto;
        return instance;
    };
}(Function.prototype.apply.bind(function () {
    var args = Array.prototype.slice.call(arguments);
    var constructor = Function.prototype.bind.apply(this, [null].concat(args));
    return new constructor;
}));

Using the above function you can create instances as follows (see the fiddle):

var f = instantiate(F, [], G.prototype);

alert(f instanceof F); // false
alert(f instanceof G); // true

f.alert(); // F

function F() {
    this.alert = function () {
        alert("F");
    };
}

function G() {
    this.alert = function () {
        alert("G");
    };
}

The above code works for user built constructors like F. However it doesn't work for native constructors like Array for obvious security reasons. You may always create an array and then change its __proto__ property but I am using this code in Rhino so it won't work there. Is there any other way to achieve the same result in JavaScript?

like image 669
Aadit M Shah Avatar asked Jul 15 '12 08:07

Aadit M Shah


People also ask

Do functions have prototype JavaScript?

A Function object's prototype property is used when the function is used as a constructor with the new operator. It will become the new object's prototype. Note: Not all Function objects have the prototype property — see description.

How do you set the prototype of one object to another in JavaScript?

The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null .

What is __ proto __ and prototype?

__proto__ is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build __proto__ when you create an object with new : ( new Foo ).

What's the difference between prototype and __ proto __ in JavaScript?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.


1 Answers

You can't fully subclass an array.

However, you can use Object.create to remove a lot of complexity from your current code (ex).

like image 58
Maël Nison Avatar answered Sep 21 '22 23:09

Maël Nison