【问题标题】:Create a JavaScript constructor function which subclasses an array创建一个继承数组的 JavaScript 构造函数
【发布时间】:2012-05-31 04:16:43
【问题描述】:

我想在 javascript 中创建一个构造函数,它具有 .prototype 属性,并且可以与 new 关键字一起使用来创建在其原型链中具有此属性的新对象。我也希望这个对象继承一个数组。

我已经能够创建一个子类数组的对象(所有需要的功能都有效) 我还没想好怎么让这个对象充当一个函数,这样它就可以作为一个构造函数了。

SubArray = function() {this.push.apply(this, arguments);};
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.constructor = SubArray;
SubArray.prototype.last = function(){return this[this.length -1]};

var arr = new SubArray(0); // [0]
arr.push(1,2,3); // [0,1,2,3]
console.log(arr, arr.length); // [0,1,2,3], 4
arr.length = 2;
console.log(arr, arr.length); // [0,1], 2
console.log(arr.last()); // 2                                
console.log(arr instanceof Array); // true
console.log(arr instanceof SubArray);  // true

我已经读过,通过向 arr 对象添加某些键,它可以用作构造函数。 我相信我必须做这样的事情。

var arrayFunction = new SubArray(0); // [0]
arrayFunction.prototype = {
    constructor: arrayFunction,
    //shared functions
};
arrayFunction.call = function(){//this would be the constructor?};
arrayFunction.constructpr = function(){//I remember seeing this as well, but I can't find the original source where I saw this};

非常感谢您对如何做到这一点的任何见解,在此先感谢您的帮助

【问题讨论】:

  • 一个更简单的问题可能是,可以通过添加call等方法将javascript对象变成构造函数吗?
  • ——我对此表示怀疑。与new 一起使用的对象必须实现一个内部[[Construct]] 方法(ES5 11.2.2),只有Functions 有这样的方法(它在Function.prototype 上)。
  • 那很不幸,我想我必须满足于我现在所拥有的。如果这是一个答案,我会接受。

标签: javascript inheritance


【解决方案1】:

我记得 John Resig 曾尝试为 Jquery 子类化一个数组,但发现这是不可能的。

【讨论】:

  • 我上面的代码创建了一个相当实用的 Array 子类,唯一不起作用的(据我所知)是当您执行以下操作时: arr = new SubArray(1,2, 3); arr[10] = 10; arr 将是 [1,2,3] 而不是 [1,2,3,undefined,...,10]。我的问题更多是关于同时对数组和函数进行子类化
  • 请注意,在声明 arr[10]=10; 之后,成员 3 到 9 未定义(即它们不存在),因此等效的数组文字将是 [1,2,3,,,,,,,10],中间成员被有效地省略.
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多