Я пытаюсь достичь некоторой степени наследования в JavaScript, и вот что у меня есть:
function Address() {
this.address1 = ko.observable();
this.address2 = ko.observable();
this.country = ko.observableSafe(null, new Country(-1, '', false));
this.city = ko.observable('');
this.state = ko.observable();
this.province = ko.observable('');
this.zipCode = ko.observable();
this.countryLookupID = '';
this.stateLookupID = '';
ko.computed(function () {
var newCountry = this.country();
if (newCountry) {
this.countryLookupID = newCountry.id.toString();
if (newCountry.international) {
this.clearDomestic();
}
else {
this.clearInternational();
}
}
else {
this.countryLookupID = "";
}, this);
ko.computed(function () {
var newState = this.state();
if (newState) {
this.stateLookupID = newState.id.toString();
}
else {
this.stateLookupID = "";
}
}, this);
}
Address.prototype.clearDomestic = function () { return true; };
Address.prototype.clearInternational = function () { return true; };
function Company() {
this.base = Address;
this.base(this);
this.legalEntityID = ko.observable(0);
this.legalEntityName = ko.observable('');
this.isFemaleOwned = ko.observable(false);
this.isMinorityOwned = ko.observable(false);
this.webAddress = ko.observable();
this.businessPhone = ko.observable();
this.faxNumber = ko.observable();
this.locked = ko.observable(false);
}
Company.prototype.constructor = Address;
Company.prototype.clearDomestic = function () {
this.businessPhone('');
this.state(null);
this.zipCode('');
};
Company.prototype.clearInternational = function () {
this.province('');
};
Если вы не знакомы с платформой Knockout, это нормально, поскольку, вероятно, нетотношение к этой дискуссии.Я нигде не видел, чтобы наследование делалось так, как я.В настоящее время это работает именно так, как вы думаете, должно.Когда вызывается clearDomestic()
, правильная версия функции вызывается в унаследованном классе, а this
указывает на объект Company
.Если я достану base
и позвоню base(this)
, он сломается.
Кто-нибудь может объяснить, почему это работает?Если это плохая практика, может кто-нибудь сказать мне, как переписать его, чтобы он функционировал так же?Я действительно не хочу включать другую библиотеку для достижения этой цели.
ОБНОВЛЕНИЕ
Если внутри Address
вы вызываете this.clearDomestic()
за пределами ko.computed
,он пытается вызвать clearDomestic()
, прикрепленный к Company
, но затем this
указывает на объект Address
, поэтому businessPhone
больше не определяется.
UPDATE 2
Я снова переместил вещи и остановился на этом методе.Это не идеально, но это единственный способ, который последовательно работает.
function Address() {
this.address1 = ko.observable();
this.address2 = ko.observable();
this.country = ko.observableSafe(null, new Country(-1, '', false));
this.city = ko.observable('');
this.state = ko.observable();
this.province = ko.observable('');
this.zipCode = ko.observable();
this.countryLookupID = '';
this.stateLookupID = '';
}
Address.prototype.clearDomestic = function () { return true; };
Address.prototype.clearInternational = function () { };
function Company() {
this.legalEntityID = ko.observable(0);
this.legalEntityName = ko.observable('');
this.isFemaleOwned = ko.observable(false);
this.isMinorityOwned = ko.observable(false);
this.webAddress = ko.observable();
this.businessPhone = ko.observable();
this.faxNumber = ko.observable();
this.locked = ko.observable(false);
ko.computed(function () {
var newCountry = this.country();
if (newCountry) {
this.countryLookupID = newCountry.id.toString();
if (newCountry.international) {
this.clearDomestic();
}
else {
this.clearInternational();
}
}
else {
this.countryLookupID = "";
}
}, this);
ko.computed(function () {
var newState = this.state();
if (newState) {
this.stateLookupID = newState.id.toString();
}
else {
this.stateLookupID = "";
}
}, this);
}
Company.prototype = new Address;
Company.prototype.clearDomestic = function () {
// Since we are entering this method via Address, we need a reference back to a real company object with self.
this.businessPhone('');
this.state(null);
this.zipCode('');
};
Company.prototype.clearInternational = function () {
this.province('');
};
Я собираюсь выполнить логику в newstate
и newcountry
в каждом объекте, который наследуется от Address
что делает это далеко от идеала, но пока я не найду лучшего предложения, я застрял с этим.