Use of this Javascript

2019-07-20 05:54发布

问题:

New to JS.. can anyone tell me if the use of this is appropriate in the below function:

var Vector = (function()...

this.prototype.add = function(someVector2){

    var tmpVect = this;
    tmpVector.x += someVector2.x;
    tmpVector.y += someVector2.y;
    return tmpVect;
};

In the sense that 'var tmpVect = this' will result in a local Vector variable with the x & y attributes of the vector that called the function?

Cheers

回答1:

I would rewrite this like so:(based on your comments)

var Vector = function(){

}

Vector.prototype.add = function(someVector2){
    var tmpVector = new Vector;
    tmpVector.x =  this.x + someVector2.x;
    tmpVector.y = this.y + someVector2.y;

    return tmpVector;
}

Then you could invoke it like so:

var someVector = new Vector();
var addedVector = someVector.add(someVector);

The above would store a new Vector in addedVector that would have an x and y value double that of someVector.



回答2:

New objects are only declared in very explicit ways; "new Vector()", or "variable = {x:5, y:2}", etc. Whenever you write "something = somethingElse", no new objects are going to be created. You can even confirm this using the triple-equals comparator.

v1 = new Vector(1, 2);
v2 = new Vector(1, 2);
v1 === v2 // will return false

v3 = v1;
v1 === v3 // will return true

v1.x = 17;
v3.x // will return 17

For ease of development, you might define a Vector prototype function "clone", that creates and returns a "new Vector()" with the same x and y as the original. If you want a new one for add()'s return, you'll need to do something like that.

Also: ryan's answer is tangentially correct - you should only define prototype functions once, not every time a Vector is created.



回答3:

Below is how I would write it. It also has a trick I read about from David Herman for making your constructors new agnostic. This means you don't necessarily have to make a new Vector with the new keyword.

function Vector(x,y) {
  // Make the constructor `new` agnostic
  if (!(this instanceof Vector)) {
    return new Vector(x,y);
  }

  this.x = x;
  this.y = y;

  return this;
}

Vector.prototype.add = function(someVector2) {
  this.x += someVector2.x;
  this.y += someVector2.y;

  return this;
};

// Example
var myVector = new Vector(1,2);
var myOtherVector = Vector(1,2);

myVector.add(myOtherVector);