javascript渴望分配

javascript eager assignment

本文关键字:分配 渴望 javascript      更新时间:2023-09-26

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

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

它工作得很好,而且它比一系列坐标更有可读性。然而,现在我希望能够通过对其反向自身:

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

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

问候,Jeroen。

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

不是很优雅,但给你。

但我想知道有没有构造其他且比上面短到立即将新对象分配给变量定义?

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


你也可以这样做:

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

您可以按照的方式编写duplicate方法

Path.prototype.duplicate = function () {
    var clone = this.clone().reverse();
    this.concat(clone);
    return this;
}

然后调用`var myPath=new Path((.move((.line((.etc((.deplicate((.