首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我是否应该使用prototype?

我是否应该使用prototype?
EN

Stack Overflow用户
提问于 2011-01-14 20:30:14
回答 2查看 9.5K关注 0票数 51

我正在创建一个Vector类,它基本上可以容纳三个数值。然而,可以对这样的向量执行许多操作-例如,获取幅值,添加或减去另一个向量等。

我想知道这些函数是应该编码为Vector类的原型函数,还是应该在构造函数中定义它们。

那么这两种方法中哪一种更可取呢?

function Vector3D(x, y, z) {
    this.x = x;
    this.y = y
    this.z = z;
}

Vector3D.prototype.magnitude = function() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};

function Vector3D(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;

    this.magnitude = function() {
        return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
    };
}
EN

回答 2

Stack Overflow用户

发布于 2011-01-14 20:33:53

原型化方法仅适用于公共属性,如果您将x,y,z作为“私有”变量来跟踪,则原型将无法工作。

我会使用后者,因为您可能需要只使用私有/内部变量的方法,但这完全取决于上下文。

function Vector3D(x, y, z) {
   // x, y, z is automatically in this scope now, but as private members.
   this.magnitude = function() {
        return Math.sqrt(x * x + y * y + z *z);
   }
}
票数 9
EN

Stack Overflow用户

发布于 2017-02-22 21:24:37

ECMA 6 http://es6-features.org/#BaseClassAccess

class Shape {
    …
    toString () {
        return `Shape(${this.id})`
    }
}
class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        super(id, x, y)
        …
    }
    toString () {
        return "Rectangle > " + super.toString()
    }
}
class Circle extends Shape {
    constructor (id, x, y, radius) {
        super(id, x, y)
        …
    }
    toString () {
        return "Circle > " + super.toString()
    }
}

ECMA 5

var Shape = function (id, x, y) {
    …
};
Shape.prototype.toString = function (x, y) {
    return "Shape(" + this.id + ")"
};
var Rectangle = function (id, x, y, width, height) {
    Shape.call(this, id, x, y);
    …
};
Rectangle.prototype.toString = function () {
    return "Rectangle > " + Shape.prototype.toString.call(this);
};
var Circle = function (id, x, y, radius) {
    Shape.call(this, id, x, y);
    …
};
Circle.prototype.toString = function () {
    return "Circle > " + Shape.prototype.toString.call(this);
};
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4691044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档