PI.
PI.

Reputation: 1668

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

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?

Upvotes: 5

Views: 1575

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

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.)

Upvotes: 5

Related Questions