使用此 Javascript [英] Use of this Javascript

查看:31
本文介绍了使用此 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JS 新手.. 谁能告诉我在下面的函数中使用 this 是否合适:

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

从某种意义上说,'var tmpVect = this' 将产生一个带有 x & 的局部 Vector 变量.调用函数的向量的 y 属性?

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?

干杯

推荐答案

我会这样重写:(基于你的评论)

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

上面将在 addedVector 中存储一个新的 Vector,它的 xy 值是 someVector.

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

这篇关于使用此 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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