【问题标题】:Prototype-based inheritance specified in the function declaration函数声明中指定的基于原型的继承
【发布时间】:2013-07-27 17:19:31
【问题描述】:

假设我有一个像这样的“类”(我正在使用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();

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

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

  return function() {

    this.color = 0;

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

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

如果我运行它,myClass 不会继承 superclass 的任何方法。为什么?

提前致谢。

【问题讨论】:

    标签: javascript inheritance requirejs prototype


    【解决方案1】:

    你为什么不干脆:

    define(['superclass'], function(superclass) {
    
      var myClass = function() {
    
        this.color = 0;
    
        this.setColor = function(color) {
          this.color = color;
        }
    
    
      };
    
      myClass.prototype = new superclass;    
      return myClass;
    
    });
    

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

    【讨论】:

      【解决方案2】:

      这会起作用(至少在 FF 和 Chrome 中)。但是请注意,每个实例都有自己的原型——在大多数情况下这是不必要的复杂化。

      define(['superclass'], function(superclass) {
      
        return function() {
      
          this.color = 0;
      
          this.setColor = function(color) {
            this.color = color;
          }
      
          this.__proto__ = new superclass;
        };    
      });
      

      prototype 是构造函数的属性。它不对应于对象的原型。 __proto__ 有,但还没有标准化。

      【讨论】:

        猜你喜欢
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 2022-02-20
        • 2021-01-27
        • 2021-11-10
        • 1970-01-01
        • 2014-06-29
        相关资源
        最近更新 更多