给定简单的 JS 继承,这两个示例之间的基本函数有什么实际区别?换句话说,一个人什么时候应该选择在“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);
原型上定义的函数:
//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);