Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
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/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!