javascript - 使用下划线继承

标签 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;

})();

我想使用 _.extend 从那个类继承

Zoo.Controllers.WhaleController = _.extend({

  new: function () {
    // do something
  }

}, Zoo.Controller);

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

this.whale_controller = new Zoo.Controllers.WhaleController();

我明白了-

Uncaught TypeError: object is not a function

是否可以做我正在尝试的事情?我已经阅读了多篇关于 JS 继承的文章,但假设 Underscore 库已经为我解决了它。

最佳答案

正如 Bergi 指出的那样;在 JavaScript 中继承并不难。您应该知道构造函数的作用以及原型(prototype)的用途。 This answer可能会有所帮助,我尝试通过简单且希望易于理解的示例来演示原型(prototype)。您可以将代码复制并粘贴到浏览器的 JS 命令行(在控制台中)并更改它以查看您是否了解原型(prototype)在 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
};

Object.create 的 Polyfill here .

关于javascript - 使用下划线继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473857/

相关文章:

javascript - 为什么在 node.js v4.0.0 中弃用了许多 util.is* 函数?

c++ - 调用基类方法而不是派生方法,即使通过引用传递也是如此

java - 如何在Java中的不同子对象之间放置不同的父对象中的静态变量

javascript - 在 Javascript 中将 json 字符串转换为对象

javascript - 如何重写 URL 的一部分?

javascript - 如何将一个十六进制数压缩成一个短字符串?

Javascript:在本地存储一个整数数组,以便可以在其他地方访问它们?

c# - 如何获取链表的某一部分

javascript - 将多个数组与javascript合并

javascript - 使用下划线js或lodash将对象解析为数组