我已经上课了-
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/