GETah
GETah

Reputation: 21409

Inheritance issue with RequireJs and Knockout

I have a requirejs module that I use as a factory to create objects of different types, the factory is illustrated below:

requirejs.config({
    appDir: ".",
    baseUrl: "js",
    paths: { 
        'jquery': '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
        'knockout': 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.min'
    },
     'knockout': { deps: ['jquery'],exports: 'knockout' }
});

define("FruitFactory", ["knockout"], function(ko){
  function Fruit(){
    this.who = function(){ console.dir(this.fruitType()); }
    this.fruitType = ko.observable();
  }
  function Apple(t){
    Fruit.call();
    this.fruitType(t);
  }
  Apple.prototype = new Fruit();
  Apple.prototype.constructor = Apple;
  function createApple(t){
    return new Apple(t);
  }
  return {  createApple: createApple }
});

require(["FruitFactory"], function(factory) {
    var golden = factory.createApple("Golden Delicious");
    var honey = factory.createApple("Honeycrisp");
    golden.who();
    honey.who();    
    return {};
});

Output:

Honeycrisp
Honeycrisp 

Why is golden.who() yielding Honeycrisp instead of Golden Delicious?

Full jsfiddle here: https://jsfiddle.net/t2xsr7uz/7/

Upvotes: 0

Views: 57

Answers (1)

user3297291
user3297291

Reputation: 23372

I think you can fix it by explicitly passing this to the Fruit.call method in your Apple constructor:

function Fruit() {
  this.who = function() {
    console.dir(this.fruitType());
  }
  this.fruitType = ko.observable();
}

function Apple(t) {
  Fruit.call(this);
  this.fruitType(t);
}
Apple.prototype = new Fruit();
Apple.prototype.constructor = Apple;

function createApple(t) {
  return new Apple(t);
}

var golden = createApple("Golden Delicious");
var honey = createApple("Honeycrisp");
golden.who();
honey.who();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Upvotes: 1

Related Questions