javascript - 函数声明中指定的基于原型(prototype)的继承

标签 javascript inheritance requirejs prototype

假设我有一个像这样的“类”(我正在使用 RequireJS ):

myClass.js

define(function() {

  return function() {

    this.color = 0;

    this.setColor = function(color) {
      this.color = color;
    }    
  };    
});

如果我想启用继承,我可以这样做:

 // later, in another file...
 myClass.prototype = new superclass();

但是为什么我不能直接在函数声明中定义原型(prototype)呢?

define(['superclass'], function(superclass) {

  return function() {

    this.color = 0;

    this.setColor = function(color) {
      this.color = color;
    }

    this.prototype = new superclass;
  };    
});

如果我运行此命令,myClass 不会继承任何父类(super class) 的方法。为什么?

提前致谢。

最佳答案

你为什么不直接:

define(['superclass'], function(superclass) {

  var myClass = function() {

    this.color = 0;

    this.setColor = function(color) {
      this.color = color;
    }


  };

  myClass.prototype = new superclass;    
  return myClass;

});

在返回定义之前你可以做任何你想做的事情。

关于javascript - 函数声明中指定的基于原型(prototype)的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17900496/

相关文章:

c++ - "method injection"的这种虚拟继承使用模式是已知范例吗?

VS2005 中的 C# : will this() execute the base constructor code for an inherited class?

javascript - 订阅大收藏

javascript - 如何更改在 HTML 中显示所选单选按钮的指示器的颜色?

javascript - 确保 backbonejs 应用程序中没有内存泄漏

javascript - 如何读取 Require.js 配置的语言环境属性?

javascript - 如何让 requirejs 适用于第三方库 (interact.js)?

javascript - 查找孤立作用域以减少内存泄漏

python - 类方法属性继承

javascript - 定义模块并立即使用 RequireJS