Given simple JS inheritance, what's the practical difference in the base function between these two examples? In other words, when should a person choose to define a function on "this" instead of on the prototype (or the other way around)?
For me the second example is easier to digest, but how much more is there to this?
function defined on this:
//base
var _base = function () {
this.baseFunction = function () {
console.log("Hello from base function");
}
};
//inherit from base
function _ctor() {
this.property1 = "my property value";
};
_ctor.prototype = new _base();
_ctor.prototype.constructor = _ctor;
//get an instance
var instance = new _ctor();
console.log(instance.baseFunction);
function defined on prototype:
//base
var _base = function () {};
_base.prototype.baseFunction = function () {
console.log("Hello from base function");
}
//inherit from base
function _ctor() {
this.property1 = "my property value";
};
_ctor.prototype = new _base();
_ctor.prototype.constructor = _ctor;
//get an instance
var instance = new _ctor();
console.log(instance.baseFunction);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…