Mukund Kumar
Mukund Kumar

Reputation: 23201

Understanding Function.prototype.apply method in chain constructor

I don't know how to ask this question. i think it would be better understandable using example:(this example i have taken from MDN)

Function.prototype.construct = function (aArgs) {
  var oNew = Object.create(this.prototype);
  this.apply(oNew, aArgs);
  return oNew;
};
function MyConstructor() {
  for (var nProp = 0; nProp < arguments.length; nProp++) {
    this['property' + nProp] = arguments[nProp];
  }
}

var myArray = [4, 'Hello world!', false];

i can create object using two way:

  1. var obj1=new MyConstructor(4,'Hello world!', false);
  2. var myInstance = MyConstructor.construct(myArray);

what is the difference between creating object using these two way ? why we use apply method to create object in chain constructor and what is advantage of creating object using 2nd way ?

Upvotes: 4

Views: 109

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

what is the difference between creating object using these two way ?

Fundamentally, the difference is whether you give the arguments as discrete arguments (#1) or as an array (#2). Also, the first way is standard, normal JavaScript; the second requires that you extend the Function prototype.

why we use apply method to create object in chain constructor

So that the arguments are passed to the constructor function as though they'd been provided as discrete arguments.

This is fairly complex code, so a simpler example of what Function#apply does is probably useful. Let's take a boring function:

function foo(a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

Now, let's call that with discrete arguments:

foo(1, 2, 3);

...which gives us

1
2
3

Now, let's use apply (ignore the null for now):

var a = [1, 2, 3];
foo.apply(null, a);

We get the same result:

1
2
3

Function#apply accepts the value to use as this as the first argument, and the arguments for the call as an array (or array-like object) in the second argument, and calls the function with that this value and arguments.

and what is advantage of creating object using 2nd way ?

Just that you can use an array for the arguments, rather than listing them individually.

Upvotes: 5

Related Questions