JavaScript .apply or .call methods

Using .apply or .call methods in JavaScript constructors and functions

by jasdeepkhalsa

JavaScript

/**** Simple Constructor ****/

function construct(prop1, prop2, prop3) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
}
var _1 = new construct();
var _2 = new construct();
construct.apply(_1, ['one', 'two', 'three']);
construct.call(_2, 'one', 'two', 'three');
console.log(_1);
console.log(_2);

/**** Function ****/
function do_something(a, b, c) {
    return console.log(a + b + c);
}

do_something.apply(this, [' one ', ' two ', ' three ']);

do_something.call(this, ' one ', ' two ', ' three ');

/**** Constructor with args ****/

function construct_args(prop1, args) {
    this.prop1 = prop1;
    var num = 2;
    for (var prop = 0; prop < args.length; prop++) {
        this['prop' + num] = args[prop];
        ++num;
    }
    return console.log(this);
}
var _3 = new construct_args('one', ['two', 'three']);

/**** Anonymous Constructor with .apply() ****/

var args = ['one', 'two', 'three'];
var _4 = new $constructor;
(function(prop1, prop2, prop3) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
    return console.log(this);
}).apply(_4, args);