1

In some JavaScript I see:

var passport = require('passport')

function Strategy(options, verify) {
  //...

  passport.Strategy.call(this);
}

What is passport.Strategy.call(this); doing?

laggingreflex
  • 32,948
  • 35
  • 141
  • 196
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 2
    It's defining instance properties on `this`. See [Define Private field Members and Inheritance in JAVASCRIPT module pattern](http://stackoverflow.com/questions/12463040/define-private-field-members-and-inheritance-in-javascript-module-pattern) – Bergi Feb 07 '14 at 14:23
  • 2
    Assuming that `passport.Strategy` is a "base" class and the user-defined `Strategy` should be an "extension", it is basically giving the extended class the features of the base one – Niccolò Campolungo Feb 07 '14 at 14:23
  • 2
    And you may find explanation on [this page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) too – Laurent S. Feb 07 '14 at 14:23
  • Begi: `call` Invokes the given function in with `this` defined for the invocation. This appears to be a "base-class constructor invocation". How is this defining "instance properties on this"? – Ben Aston Feb 07 '14 at 14:38
  • You have two answers saying significantly different things, and I want to point out that they're both likely correct. Niels correctly points out the only thing we know for certain. `passport.Strategy` is being called with the `this` object being set to the `this` object that was used when `Strategy` was called. That's all we can be entirely certain of. But badsyntax is most likely correct too that the capitalization of both `Strategy`'s is means that this is being done in order to run `passport.Strategy` as a constructor function inside the `Strategy` constructor. – Scott Sauyet Feb 07 '14 at 14:56

2 Answers2

3

In the context of that code, this is effectively a way to execute the super constructor. Looking at the passport-local object for example, the passport-local class's prototype inherits from the Strategy prototype. Effectively it's a "sub-class" of passport.Strategy. When you create a new instance of passport.Local, you will also want to execute the super constructor (passport.Strategy). Doing constructor.call(context) allows you to execute the super constructor in the context of the sub-class.

badsyntax
  • 9,394
  • 3
  • 49
  • 67
1

The .call() function is a native javascript function which passes the context to the function. In this case the function passport.Strategy() is called and the context of this is passed.

This means that within the passport.Strategy() function the this object refers to the first passed variable to the .call() function.

Niels
  • 48,601
  • 4
  • 62
  • 81