【问题标题】:Class inheritance in Prototype.js and arraysPrototype.js 和数组中的类继承
【发布时间】:2010-11-23 09:43:40
【问题描述】:

我正在使用 Prototype.js(来自 www.prototypejs.org)库来创建由子类扩展的类。不过,我在这些类的实例中使用数组时遇到了麻烦。我做了一个例子来说明这一点:

var SuperClass = Class.create({
    initialize: function(id) {
        this.id = id;
    }
});

var SubClass = Class.create(SuperClass, {
    items: [],

    add: function(arg) {
        this.items[this.items.length] = arg;
    },

    initialize: function($super, id) {
        $super(id);
    }
});

var a = new SubClass("a");
var b = new SubClass("b");

a.add("blah");
alert(a.id + ": " + a.items.length);
alert(b.id + ": " + b.items.length);

这里的问题是,第一个和第二个警报都将表明它们各自的对象在它们的 items 数组中有 1 个项目,即使我只向对象 a 添加了一个项目。原始数据类型可以正常工作(如正确显示的 id 属性所示),但数组无法正常工作。我是否将 items 数组和 add 方法移动到超类也没关系,我已经尝试过了。

有没有办法让它工作?这是 Prototype 中的错误还是 JavaScript 的本质? :-)

【问题讨论】:

    标签: javascript arrays class prototypejs


    【解决方案1】:

    传递给 Class.create 的对象字面量的成员被添加到 SubClass 的原型中,因此您的所有对象都将共享 items-array。您可以通过将 items-definition 移至构造函数来解决这种情况:

    var SubClass = Class.create(SuperClass, {
    
        add: function(arg) {
            this.items[this.items.length] = arg;
        },
    
        initialize: function($super, id) {
            $super(id);
            this.items = [];
        }
    });
    

    【讨论】:

    • 哇,快速回答。还有对的!非常感谢,真的很感激。
    【解决方案2】:

    我不是原型用户,但是... JavaScript 是一种原型语言。这意味着它使用原型继承。换句话说,对象从对象继承,或者对象从其他对象继承状态和行为。在您的情况下,对象 ab 都将继承自 Class.create(SuperClass, {}) 中以文字表示法声明的对象,因此 items 将在两者之间共享,因为 MyClass 的每个实例都继承自该对象文字。

    这里有一些例子:

    var Foo = function (name) {
        this.name = name;
    };
    
    var Bar = function () {};
    Bar.prototype = new Foo("John");
    
    var a = new Bar;
    var b = new Bar;
    
    alert(a.name); // John
    alert(b.name); // John
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多