开发者

javascript eager assignment

Influenced by jQuery, I'm experimenting with method chaining in javascript. I constructed a wrapper around an array which will accept coordinate points and transform methods. It's general syntax is something like:

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

it works well, and it makes it somewhat more readable than a string of coordinates. However now I want to be able to duplicate the existing path by doing a concatenation of its reversed self:

// create a symmetrical path.
myPath = new Path().move().line().etc().etc.concat(my开发者_StackOverflowPath.reverse());

But that fails because myPath is unknown as argument to concat. It works when i do:

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

But I'm wondering is there a construct other and shorter than above to immediately assign the new Object to the variable definition? If its not possible in Javascript, i'd be interested if it's possible in other languages?

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

Not very elegant, but here you go.

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

No, you can't reference what hasn't been created yet.


You could do this as well:

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


You might code a duplicate method along the lines of

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

and then call `var myPath = new Path().move().line().etc().duplicate().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜