Should I use prototype or not?

后端 未结 3 1282
Happy的楠姐
Happy的楠姐 2020-11-29 00:47

I\'m creating a Vector class, which can basically hold three numerical values. However, a lot of operations can be done on such a vector - e.g. getting the magnitude, adding

3条回答
  •  情话喂你
    2020-11-29 01:46

    Prototyped methods would only work for public properties, if you would keep track of x, y, z as "private" variables the prototype would not work.

    I would use the latter, because you might want methods that only work with private/internal variables, but it all depends on context.

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

提交回复
热议问题