【问题标题】:In Javascript, how can you inherit and extend a method that is being inherited?在 Javascript 中,如何继承和扩展被继承的方法?
【发布时间】:2012-07-20 21:34:50
【问题描述】:

不幸的是,我已经四处搜索,但没有找到此问题的重复项。

文件1:

var Graph = Backbone.View.extend({
  move: function() {
    //some stuff
  }, //more stuff
})

文件 2:

define ([ './graph.js' ]), function( graph ) {
  var SubGraph = Backbone.View.extend({
// this file needs to inherit what is within the move method but extend it to include other stuff
   })

如何在不破坏现有属性的情况下扩展继承的属性?

【问题讨论】:

  • 您能否详细说明您的期望?
  • 我认为你可以做var SubGraph = Graph.extend(...,以设置继承,但我不确定......(我过去只处理过一次Backbone)

标签: javascript oop backbone.js prototype


【解决方案1】:

看起来你正在使用 Require.js

做:

图表模块:

define(function() {
  return Backbone.View.extend({
    move: function() {
    //some stuff
  }
});

子图模块:

define(['require', './graph'], function(require) {
  var Graph = require('./graph');

  return Graph.extend({
    // this file needs to inherit what....
  }
});

或者如果你没有定义很多依赖,就不要包含require

define(['./graph'], function(Graph) {
  return Graph.extend({
    // this file needs to inherit what....
  }
});

【讨论】:

  • 有没有办法在 move 方法中扩展语句?例如:Graph 的 move 方法包含一个语句 this.model.save({}),它保存 x 和 y 坐标,我想从 subgraph 的 move 方法中扩展该语句或替换它以包含 z 坐标;这是图形对象当前包含的内容: move: function(){this.model.save({x-coord: this.deltaX, y-coord: this.deltaY})
  • 你不能扩展它,因为它是一个函数而不是一个构造函数。如果您使用move 作为var moveA = new move(),您可以使用move.prototype.newMethod = function()...,但看起来情况并非如此。
  • 为了清楚起见,我需要做任何事情来移动:graph.js 中的 function() {...} (这在技术上被认为是构造函数吗?)或者只是做 var moveA =新动作();在 subgraph.js 中移动:function(){//一些额外的功能}?感谢您抽出宝贵时间回复!
  • 如果你不需要修改move,你在修改Graph.extend的时候就已经有了。你的问题是关于。修改它——但是如果你想修改move,那么为什么你首先需要扩展Graph?您通常扩展,因为您不需要修改您扩展的类的大部分方法))
  • move 有几个我想在子图和其他视图中继承和使用的语句,只是需要更改的 'this.model.save...' 语句
猜你喜欢
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多