In JavaScript, most functions are callable and realistic: they have both [[Call]] and [[Construct]] internal methods.
As called objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value .
var player = makeGamePlayer("John Smith", 15, 3);
The above code calls the makeGamePlayer function and stores the return value in the player variable. In this case, you can define the function as follows:
function makeGamePlayer(name, totalScore, gamesPlayed) {
In addition, when calling a function, you also pass an additional argument under the hood, which defines the value of this inside the function. In the above case, since makeGamePlayer not called as a method, this value will be a global object in inactive mode or undefined in strict mode.
As constructors, you can use the new operator to create them. This statement uses the internal [[Construct]] method (available only in constructors), which does something like this:
- Creates a new object that inherits from the
.prototype constructor - Invokes a constructor that passes this object as the value of
this - Returns the value returned by the constructor if it is an object or an object created in step 1 otherwise.
var player = new GamePlayer("John Smith", 15, 3);
The above code creates an instance of GamePlayer and stores the return value in the player variable. In this case, you can define the function as follows:
function GamePlayer(name,totalScore,gamesPlayed) { // `this` is the instance which is currently being created this.name = name; this.totalScore = totalScore; this.gamesPlayed = gamesPlayed; // No need to return, but you can use `return this;` if you want }
By convention, the names of the constructors begin with a capital letter.
The advantage of using constructors is that instances inherit from GamePlayer.prototype . Then you can define the properties there and make them available in all instances.