I am using:
var ReportsServiceCall = function () { };
ReportsServiceCall.prototype = new ServiceCall();
With this code, is the ServiceCall
a fresh instance each time a new ReportsServiceCall
is created? I need it to be so.
I am using:
var ReportsServiceCall = function () { };
ReportsServiceCall.prototype = new ServiceCall();
With this code, is the ServiceCall
a fresh instance each time a new ReportsServiceCall
is created? I need it to be so.
Nope
As you have it written, the prototype is only setup once. However, that's not a very good way to write it.
I would write it like this
var ReportsServiceCall = function () {
// parent constructor; optional
ServiceCall.call(this);
};
// setup prototype; see comment below
ReportsServiceCall.prototype = Object.create(ServiceCall.prototype, {
constructor: {
value: ReportsServiceCall,
enumerable: false,
writable: true,
configurable: true
}
});
Note: Aside from setting super_
, this is how node.js is doing vanilla inheritance in their util.inherits function.
This is very effective technique once you understand how it works.
With this code, is the ServiceCall a fresh instance each time?
No and it's not a good way to setup inheritance. At the moment you are calling new ServiceCall
, you actually don't want to create an instance of ServiceCall
(which arguments would you pass if the constructor requires parameters?). All you really want is add ServiceCall
's prototype to ReportsServiceCall
's prototype chain.
You should use Object.create
instead and call the superclass constructor inside the child class constructor:
var ReportsServiceCall = function () {
ServiceCall.call(this);
};
ReportsServiceCall.prototype = Object.create(ServiceCall.prototype);
See Benefits of using `Object.create` for inheritance for an extended explanation of this pattern.
The prototype is only a single object that will be shared by all of the instances of ReportsServiceCall
. If you need the ServiceCall
constructor to be called for each ReportsServiceCall
instance, you can do this:
function ReportsServiceCall() {
ServiceCall.call(this);
};
ReportsServiceCall.prototype = new ServiceCall();
ReportsServiceCall.prototype.constructor = ReportsServiceCall;
Not really.
A ReportsServiceCall
is a ServiceCall
, but create a ReportsServiceCall
with new
doesn't make it have its own properties which assigned in the constructor of ServiceCall
.
Look at the following example:
var ServiceCall=function () {
this.Id=Math.random();
};
var ReportsServiceCall=function () {
};
ReportsServiceCall.prototype=new ServiceCall();
var x=new ReportsServiceCall();
var y=new ReportsServiceCall();
alert(x.Id===y.Id); // true .. so, what Id for?
One of the solutions is:
var ReportsServiceCall=function () {
ServiceCall.apply(this, arguments);
};