I have some code like this:
var A = function(a,b,c) {
var self = this;
self.a = ko.observable(a);
...
self.function1 = ko.computed(function () {
dothing(a);
...
}
self.function2 = ko.computed(function () {
dothing(b);
...
}
}
var B = function(a,b,c,d) {
var self = this;
self.a = ko.observable(a);
...
self.function1 = ko.computed(function () {
dothing(a);
...
}
self.function2 = ko.computed(function () {
dothing(b);
...
}
}
How can I "extract" function1 and function2 to a function that A and B can share?
That's just where prototypes fit in:
Having said that, personally, I prefer to define my constructors regularly:
Whereas your code assigns an anonymous function to a variable, which means that the constructor doesn't have a name:
It's not that big of a deal, but just so you know...
Reference a method from the global (or any other) scope:
The closure will be accessible (exposed), still, but be very careful with
this
:An other possibility is "borrowing" a function:
Again, be careful: in this case
this
logsB
, butself
still referencesA
! You could build in certain "safety nets":But honestly, you might do well reading up on the this operator to grasp all this referencing trickery. It's not that hard once you get the basics. Also check the call and apply methods for more details on how to "share/borrow" methods
You could change the scope of the function by pulling it out of that object.
You could try using the underscore.js extend functionality to do the inheritance.