I have the following js inheritance example:
function Fruit(){
this.who = function(){ console.dir(this.fruitName); }
}
Fruit.prototype.fruitName = "I am a fruit";
function Orange(){
Fruit.call();
this.fruitName = "I am an orange";
}
Orange.prototype = new Fruit();
Orange.prototype.constructor = Orange;
function Apple(){
Fruit.call();
this.fruitName = "I am an apple";
}
Apple.prototype = new Fruit();
Apple.prototype.constructor = Orange;
var orange = new Orange();
var apple = new Apple();
orange.who();
apple.who();
The code above outputs:
I am an orange
I am an apple
Which is correct.
Now, changing the fruitName to a knockout observable gives an unexpected result:
function Fruit(){
this.who = function(){ console.dir(this.fruitName()); }
}
Fruit.prototype.fruitName = ko.observable("I am a fruit");
function Orange(){
Fruit.call();
this.fruitName("I am an orange");
}
Orange.prototype = new Fruit();
Orange.prototype.constructor = Orange;
function Apple(){
Fruit.call();
this.fruitName("I am an apple");
}
Apple.prototype = new Fruit();
Apple.prototype.constructor = Orange;
var orange = new Orange();
var apple = new Apple();
orange.who();
apple.who();
Output:
I am an apple
I am an apple
Unless I am doing something wrong, this looks like a bug in Knockout. Is there a way around this issue?
Full jsfiddle available here: https://jsfiddle.net/h1go9se2/
The idea of the prototype is that it's shared between instances. Functions use this to make sure running the methods actually impacts a single instance.
Knockout observables are functions, but they're best thought of as wrappers around a value.
If you define your observable on the prototype, it means you're wrapping a value to be shared by all instances.
Writing to that value in the constructor of any class that extends it will overwrite the value for all instances.
Instead of declaring fruitName on the Fruit prototype, you define the property inside the Fruit constructor:
function Fruit(){
this.who = function(){ console.dir(this.fruitName()); }
this.fruitName = ko.observable("I am a fruit");
}
Runnable snippet:
function Fruit(){
this.who = function(){ console.dir(this.fruitName()); }
this.fruitName = ko.observable("I am a fruit");
}
function Orange(){
Fruit.call();
this.fruitName("I am an orange");
}
Orange.prototype = new Fruit();
Orange.prototype.constructor = Orange;
function Apple(){
Fruit.call();
this.fruitName("I am an apple");
}
Apple.prototype = new Fruit();
Apple.prototype.constructor = Orange;
var orange = new Orange();
var apple = new Apple();
orange.who();
apple.who();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>