这是' subclass'的合理方法吗?一个JavaScript数组? [英] Is this a reasonable way to 'subclass' a javascript array?

查看:47
本文介绍了这是' subclass'的合理方法吗?一个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 vector,而不是普通数组,并且对vector特定的原型函数也进行了相同的操作,那么应该相当容易跟踪.

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());

这篇关于这是&amp;#39; subclass&#39;的合理方法吗?一个JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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