有人可以解释一下这些javascript概念吗?

Could someone please explain theses javascript concepts?

本文关键字:javascript 一下 解释      更新时间:2023-09-26

所以我最近一直在看这段代码,我很难理解一些东西。

当"类"第一次使用以下代码声明时,我理解:

function GravityPoint(x, y, radius, targets) {
    Vector.call(this, x, y);
    this.radius = radius;
    this.currentRadius = radius * 0.5;
    this._targets = {
        particles: targets.particles || [],
        gravities: targets.gravities || []
    };
    this._speed = new Vector();
}

我说使用Vector.call(this, x, y);是正确的,所以你不必声明位置向量?如果我理解正确,您可以致电:

var a = new GravityPoint(0,0,10,[..]);

然后a.x == 0?(假设向量具有 x 和 y 属性)

我的第二个问题是关于这段代码的:

GravityPoint.prototype = (function(o) {
    var s = new Vector(0, 0), p;
    for (p in o) s[p] = o[p];
    return s;
})({
    gravity:       0.05,
    isMouseOver:   false,
    dragging:      false,
    destroyed:     false,
    _easeRadius:   0,
    _dragDistance: null,
    _collapsing:   false,
    hitTest: function(p) {
        return this.distanceTo(p) < this.radius;
    }
    ...
});

我不明白这个结构:MyClass.prototype = (function(o){})({ prop1:val1})

对我来说,这就像将第二部分({ prop1:val1})作为参数发送到函数function(o){}这没有意义,因为该函数返回一个向量。

感谢您的帮助

它是立即调用的函数表达式或 iffy

简单示例

(function(a, b) {
  // a == 'hello'
  // b == 'world'
})('hello', 'world');

在您的情况下,您正在定义这个 iffy 函数

function(o) {
    var s = new Vector(0, 0), p;
    for (p in o) s[p] = o[p];
    return s;
}

然后用这个参数调用它,并将结果存储在GravityPoint.prototype中。

{
    gravity:       0.05,
    isMouseOver:   false,
    dragging:      false,
    destroyed:     false,
    _easeRadius:   0,
    _dragDistance: null,
    _collapsing:   false,
    hitTest: function(p) {
        return this.distanceTo(p) < this.radius;
    }
}