开发者

Theoretical question about browser javascript engines

I doubt this is possible, and I'm certain to do it in a production environment would be an impressively bad idea. This is just one of those hypothetical "I-wonder-if-I-could..." things.

I was w开发者_运维问答ondering if it is possible to modify or extend how the browser JavaScript engine parses the code at run-time. For example: if I tried to use C# style lambda syntax in JavaScript:

var x = myJsObjCollection.Where(a=>a.ID == 2);

Could I modify the parsing of the script and intercept the lambda code and parse it myself?


I doubt it.

The engine which parses and executes the javascript is on the client's browser, and as such cannot be modified or changed by any website (I would hope).

Potentially you could use javascript supported types and syntax to describe a lambda expression and then have your own javascript library which expands it to valid javascript calls.

However, it would not be that useful since javascript functions are already super flexible. Your code above in valid JS would look like the equivalent c# delegate:

var x = myJsObjCollection.Where(function() { if (this.ID == 2) return this; });

Which isn't a whole lot more work to type.

Update

To take Bob's Idea a couple steps further, you could potentially write something like this:

function lambda(vName, comparison)
{
    var exp = new RegExp("\\b" + vName + "\\.", "g");
    comparison = comparison.replace(exp, "arg.");
    return function(arg) {
        var result;
        eval("result = " + comparison + ";");
        return result;
    };
}

Then your Where function would look something like:

Array.prototype.Where = function(lambdaFunc) {
    var matches = [];    
    for (var i in this)
    {
        if (lambdaFunc(this[i]))
            matches[matches.length] = this[i]
    }
    return matches;
};

And you could call it:

var x = myJsObjCollection.Where(lambda("a", "a.ID == 2"));

Working example at http://jsbin.com/ifufu/2/edit.


There's no direct way to do this in JavaScript. The closest you could get would be to write your own eval type function which would interpret whatever code you want.

Or, get the V8 JavaScript engine source code, make some changes to that, and see if you can get it implemented in Chrome somehow :)


The answer is pretty much "no", but check this out: http://osteele.com/sources/javascript/functional/ and in particular the stuff about string -> function "coercion".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜