使用下划线继承

Fin*_*nnn 1 javascript inheritance underscore.js

我上过课 -

Zoo.Controller = (function() {

  function Controller() {}

  Controller.prototype.params = {};

  Controller.prototype.set_params = function(params) {
    this.params = params;
    return this;
  };

  return Controller;

})();
Run Code Online (Sandbox Code Playgroud)

我想使用_.extend从该类继承

Zoo.Controllers.WhaleController = _.extend({

  new: function () {
    // do something
  }

}, Zoo.Controller);
Run Code Online (Sandbox Code Playgroud)

当我尝试像这样实例化那个类时......

this.whale_controller = new Zoo.Controllers.WhaleController();
Run Code Online (Sandbox Code Playgroud)

我明白了 -

Uncaught TypeError: object is not a function
Run Code Online (Sandbox Code Playgroud)

有可能做我正在尝试的事情吗?我在JS中读过很多关于继承的文章,但是假设Underscore库已经为我解决了.

HMR*_*HMR 5

正如Bergi指出的那样; 在JavaScript中继承并不难.您应该知道构造函数的作用以及使用的原型.这个答案可能对此有所帮助,我试图通过简单且希望易于理解的示例来演示原型.您可以在浏览器JS命令行中(在控制台中)复制并粘贴代码,并更改它以查看您是否了解原型在JavaScript中的行为.

要从ZooController继承,您可以:

Zoo.Controllers.WhaleController = function(args){
  Zoo.Controller.apply(this,arguments);//re use Zoo.Controller constructor
                                  //and initialize instance variables
  //instance specific members of Whale using an args object
  this.weitht=args.weight||4;
  this.wu=args.weightUnit||wu.metricTon;
  //Zoo.Controller.call(this,arg1,arg2); can be used too but I usually use
  // an args object so every function can pick out and mutate whatever they want
  // for example: var w = new WhaleController({weight:3,weightUnit:wu.metricTon});
  // now it looks more like pythons optional arguments: fn(spacing=15, object=o)
};
//set Zoo.controller.prototype to a shallow copy of WhaleController.prototype
//may have to polyfill the Object.create method if you want to support older browsers
Zoo.Controllers.WhaleController.prototype=Object.create(Zoo.Controller.prototype);
//repair constructor
Zoo.Controllers.WhaleController.prototype.constructor=Zoo.Controllers.WhaleController;
//extend Zoo.controller.prototype.set_params
Zoo.Controllers.WhaleController.prototype.set_params=function(){
  //re use parent set_params
  Zoo.Controller.prototype.set_params.apply(this,arguments);
  //and do something extra
  console.log("extra in set_params from WhaleController");
};
//WhaleController own function
Zoo.Controllers.WhaleController.prototype.whaleSpecific=function(){
  //funciton specific to WhaleController
};
Run Code Online (Sandbox Code Playgroud)

这里使用 Polyfill for Object.create .

  • 很好的答案,代码很难阅读. (2认同)