我怎麼能在運行時爲每個實例覆蓋this.property
,未做一個新的類,並最終調用父doAnotherThing
?的Javascript原型banals:繼承
var ThridPartyObject = function() {
this.property = 'value';
this.doOneThing= function() { /* */ }
this.doAnotherThing= function() { /* */ }
};
沒有運氣:
ThridPartyObject.prototype = {
property: 'myvalue',
doOneThing: function() { // Override only this function and call the other
return this.doAnotherThing();
}
};
編輯:忘了說,property
可能會或可能不會存在。
我需要這個,因爲在Backbone.js的,我必須定義一個自定義屬性爲我所有的模型實例,以及一些功能應該在原有骨幹的人以不同的方式行事。這裏是骨幹如何定義一個Backbone.Model
(_.extend
是underscore.js):
var Model = Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (options && options.collection) this.collection = options.collection;
if (options && options.parse) attributes = this.parse(attributes);
if (defaults = getValue(this, 'defaults')) {
attributes = _.extend({}, defaults, attributes);
}
this.attributes = {};
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
this.set(attributes, {silent: true});
// Reset change tracking.
this.changed = {};
this._silent = {};
this._pending = {};
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// cut
});
假設好的(第二...),我怎麼能從doOneThing裏面調用doAnotherThing? – Polmonino 2012-08-15 22:57:12
'this.doAnotherThing()'將起作用。 – Domenic 2012-08-15 22:59:20
我做你的例子(函數覆蓋),這完全消滅了原來的類...意味着現有的實例調用不再工作... – Polmonino 2012-08-15 23:20:49