What is apply invocation pattern in Javascript in reference to function invocation patterns and how can I use it? What are the benefits of using this invocation pattern.
You can also use call/apply for inheritance.
function Client (id) {
this.id = id;
this.name = "Client" + id;
}
Client.prototype = {
constructor: Client
, toString: function () {
return this.name;
}
};
function WebClient (id) {
Client.call (this, id);
}
WebClient.prototype = new Client ();
WebClient.prototype.constructor = WebClient;
WebClient.prototype.ping = function () {
// do stuff
};
Notice Client.call (this, id);
This executes Client
using the this
instance that a new WebClient
would create. Thus when
this.id = id;
this.name = "Client" + id;
are executed inside Client
the WebClient
instance is getting assigned those properties.