Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this.constructor.prototype.constructor.apply mean in js

Tags:

javascript

I was reading this article, and I can't figure out what the below line does. Even if I remove this line, I can't see any difference.

this.constructor.prototype.constructor.apply(this,Array.prototype.slice.call(arguments));

Could someone explain me why this.constructor.prototype.constructor is necessary, wouldn't this.constructor return the same value?

like image 528
PI. Avatar asked Jun 15 '13 15:06

PI.


1 Answers

Basically, what it's trying to do is call the constructor function for the object that is the current object's prototype.

Breaking it down:

  • this - The current object
  • this.constructor - The constructor property on the current object, which is almost certainly (but not necessarily!) inherited from its prototype. And so it's probably (but not necessarily) the function that created the object.
  • this.constructor.prototype - The object assigned to that function's prototype property. (The object that will be assigned as the underlying prototype of objects created if you call that function via new.)
  • this.constructor.prototype.constructor - The function that created that object.

...and then we call apply on it to set this within the call to the current this, and use Array.prototype.slice to make a copy of the current arguments as a true array. (That last part is unnecessary, apply accepts anything that's array-like, it doesn't require true arrays. So the code could just use arguments directly.)

like image 50
T.J. Crowder Avatar answered Sep 24 '22 15:09

T.J. Crowder