Reputation: 363
Something I have always wondered about, how does javascript (or languages in general) use an 'alternate' syntax for declaring instantiations of built in objects? for example.
// This being the same as..
var array = new Array('hi','there');
// This.
var array = ['hi','there'];
// or
var myFun = new Function("a","b","return a * b");
// being the same as..
var myFun = function(a,b){ return a * b }
Is there any way I can do this if I were to work on my own library? say I wanted to make some kind new syntax for a particular thing? Is there something in the prototype method? Or is this something that is beyond the capture of the developer and only within the grasp of the W3?
John Resig's jQuery seems to have a unique syntax
$('.class').css({'color':'#000'});
Is there something a bit deeper he had to do in order to get this level of customization? or was it a matter of doing things like..
// Obviously just a very simple example.
var $ = function(param){
return document.querySelectorAll(param);
}
I would be very interested to know and look forward to hearing your answers, thank you.
Upvotes: 0
Views: 219
Reputation: 413916
No JavaScript library alters the syntax of the language, as JavaScript has no native facilities to do that. For example, jQuery "syntax" is just simple JavaScript syntax. You too can create your own function named $
, and write functions that return objects to allow that "chaining" code style.
Some languages have varyingly-powerful macro facilities that effectively do allow new syntax to be concocted. JavaScript isn't one of those languages (without some external tool).
Things like TypeScript, PureScript, and CoffeeScript are essentially pre-processors that parse a different syntax to generate plain JavaScript.
Upvotes: 5