javascript 急切赋值

标签 javascript variable-assignment

受 jQuery 的影响,我正在尝试 javascript 中的方法链接。我围绕数组构建了一个包装器,它将接受坐标点和变换方法。它的一般语法是这样的:

myPath = new Path().move({x:50,y:50}).line({x:20,y:20}).rotate(Math.PI/3);

它工作得很好,并且比坐标字符串更具可读性。但是现在我希望能够通过串联来复制现有路径 它的反转 self :

// create a symmetrical path.
myPath = new Path().move().line().etc().etc.concat(myPath.reverse());

但是失败了,因为 myPath 作为 concat 的参数是未知的。当我这样做时它就起作用了:

var myPath = new Path();
myPath.move().line().etc().etc().concat(myPath.reverse());

但我想知道是否有一个比上面更短的构造可以立即将新对象分配给变量定义? 如果在 Javascript 中不可能,我会感兴趣是否可以在其他语言中实现?

问候, 杰罗恩。

最佳答案

Path.prototype.concat = function () {
    this.concatting = true;
    return this;    
};

Path.prototype.reverse = function () {
    if (this.concatting) {
        Array.push.apply(
            this.pathArr,
            Array.slice(this.pathAr).reverse()
        );
        this.concatting = false;
    } else {
        this.pathAr.reverse();
    }

    return this;
};

var myPath = new Path().move().line().etc().concat().reverse();

不是很优雅,但你就可以了。

But I'm wondering is there a construct other and shorter than above to immediately assign the new Object to the variable definition?

不,您无法引用尚未创建的内容。


您也可以这样做:

(myPath = new Path()).move().line().etc().etc.concat(myPath.reverse());

关于javascript 急切赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6623645/

相关文章:

c++ - C++ 正十进制整数的递归函数数字逆序

python - 使用索引的 Pandas 系列替换值

javascript - 数组值更新后对 native 选择器显示使用react

javascript - ES6 结构分配?

javascript - 动态显示下拉框中的值,然后显示用户选择的已存储在数据库中的值

javascript - 无法让子钩子(Hook)接收状态

java - 为什么 Java 编译器会提示局部变量没有在这里初始化?

c - C中赋值的逻辑值

JavaScript 将日期设置为 x 的开头

javascript - 仅在第一次尝试时检查复选框,javascript/jquery bug?