这是“子类化"javascript 数组的合理方法吗? [英] Is this a reasonable way to 'subclass' a javascript array?

查看:23
本文介绍了这是“子类化"javascript 数组的合理方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到,严格来说,这不是对数组类型进行子类化,但这会以人们预期的方式工作,还是我仍然会遇到一些与 .length 之类的问题?如果可以选择正常的子类化,我会不会有任何缺点?

I realize that, strictly speaking, this is not subclassing the array type, but will this work in the way one might expect, or am I still going to run into some issues with .length and the like? Are there any drawbacks that I would not have if normal subclassing were an option?

        function Vector()
        {
            var vector = [];
            vector.sum = function()
            {
                sum = 0.0;
                for(i = 0; i < this.length; i++)
                {
                    sum += this[i];
                }
                return sum;
            }            
            return vector;
        }

        v = Vector();
        v.push(1); v.push(2);
        console.log(v.sum());

推荐答案

我会将数组包装在适当的向量类型中,如下所示:

I'd wrap an array inside a proper vector type like this:

window.Vector = function Vector() {
  this.data = [];
}

Vector.prototype.push = function push() {
  Array.prototype.push.apply(this.data, arguments);
}

Vector.prototype.sum = function sum() {
  for(var i = 0, s=0.0, len=this.data.length; i < len; s += this.data[i++]);
  return s;
}

var vector1 = new Vector();
vector1.push(1); vector1.push(2);
console.log(vector1.sum());

或者,您可以在数组上构建新的原型函数,然后只使用普通数组.

Alternatively you can build new prototype functions on arrays and then just use normal arrays.

如果您一致命名数组,因此它们都以小写 v 开头,例如或类似的东西清楚地将它们标记为 aw 向量而不是普通数组,并且您对特定于向量的原型函数执行相同操作,那么它应该相当容易跟踪.

If you are consistent with naming the arrays so they all start with a lowercase v for example or something similar that clearly mark them aw vector and not normal arrays, and you do the same on the vector specific prototype functions, then it should be fairly easy to keep track of.

Array.prototype.vSum = function vSum() {
  for(var i = 0, s=0.0, len=this.length; i < len; s += this[i++]);
  return s;
}

var vector1 = [];
vector1.push(1); vector1.push(2);
console.log(vector1.vSum());

这篇关于这是“子类化"javascript 数组的合理方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆