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?
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.
The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null .
__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 ).
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.
You can't fully subclass an array.
However, you can use Object.create to remove a lot of complexity from your current code (ex).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With