RequireJs 和 Knockout 的继承问题

Inheritance issue with RequireJs and Knockout

我有一个 requirejs 模块,用作工厂来创建不同类型的对象,工厂如下图所示:

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 {};
});

输出:

Honeycrisp
Honeycrisp 

为什么 golden.who() 产生 Honeycrisp 而不是 Golden Delicious

这里有完整的 jsfiddle:https://jsfiddle.net/t2xsr7uz/7/

我认为您可以通过显式将 this 传递给 Apple 构造函数中的 Fruit.call 方法来修复它:

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>