受 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/