Is it possible to define a new statement? - javascript

I want to be able to define a statement in javascript. For example, I want to define
a statement called file that works like a class.
function file() {
//code goes here
}
I want that to be used as a statement, like if,for,andreturn.
file filename(filename,purpose) {
//code goes here
}
Do I need to build a seperate compiler or is it possible?
Please change the title if there is a better way to say it.

What are you trying to accomplish?
You can emulate some class-like structure in JavaScript using the Revealing Module Pattern
Also, I've never seen a class work like what you've described -- typically you instantiate an object of a class, and then access the object's public properties. This can be done in JavaScript ('cept objects are created dynamically). For example:
// file 'class'
var file = function () {
var a; // private variable
function filename(name, purpose) {
// code goes here
}
// return public members
return {
filename: filename
};
};
// An object created from your 'class' with the member function 'filename()'
var aFile = file();
Then call your member function using the . operator, like so: aFile.filename(name, purpose);

This would be writing a new language based on Javascript, much like Coffeescript, among many others. Those languages need to compile to JS before being served to a web browser, for instance.
Take a look at a Coffeescript -> JS interpreter to know how to go about this. For the record, I don't think this is a good approach.
Lastly I'll note that languages like Scala have very good DSL support, meaning it's easy to add features within the language. For instance, even + in Scala is library code, not native code. (More technically, could be written that way from a language standpoint.)

I want to be able to define a statement in javascript.
I want that to be used as a statement, like if,for,andreturn.
No, you cannot do this, as a Javascript parser would not be able to parse this.
If you really wish to do this, your only option would be to create your own language, and write a transpiler from your new language to Javascript, as #djechlin has pointed out.

I believe what you want is to implement control structures rather than statements since the example you gave, if, for and return are control structures. If that is what you really mean then yes, you can do that with functions but not with the syntax you describe.
In javascript, functions are first class objects. That is, they can be assigned to variables and passed as arguments to other functions. For example, here's an implementation of if that uses no built-in control structure (no if, while, switch etc. and no ternary operator):
function IF (condition, callback) {
[function(){}, callback][+!!condition]();
}
You can use the above function as a replacement of if but the syntax is a bit unconventional:
IF ( a == b, function(){
console.log('hello');
});
But if you've been programming javascript long enough the above syntax would be familiar and you'd have encountered many similar control structures implemented as functions such as [].forEach() and setTimeout().
So, if you want to implement a control structure to parse a file for example, you can do something like this:
function parseFile (filename, callback) {
// code to process filename
callback(result);
}
Or even something like this:
function eachLine (filename, callback) {
// code to process filename
for (var i=0; i<file_content.length; i++) {
callback(file_content[i]);
}
}
which you can use like this:
eachLine("some_file.txt",function(line){
if (line.match(/hello/)) {
console.log('Found hello! This file is friendly.');
}
});

if you don't need parameters you can do:
Object.defineProperty(window, 'newcmd', {
get: () => console.log("hello")
})
newcmd

Related

Best way to chain a JavaScript function between different files

What's the best way to chain a JavaScript function between different files? In this case, BusinessObjectCategories() and BusinessAddSiteStatusFunctionalities() are undefined because the function is in another page. Should I get the global object in JavaScript?
**Doo.js**
var Doo = new DooObject();
**Doo.Business.js**
function BusinessObject() {}
if (typeof Doo != undefined) {
Doo.Business = new BusinessObject();
BusinessObjectCategories();
}
**Doo.Business.Categories.js**
function BusinessObjectCategories() {}
if (typeof Doo != undefined) {
Doo.Business.Categories = new BusinessObjectCategories();
BusinessAddSiteStatusFunctionalities();
}
**Doo.Business.Categories.SiteStatus.js**
function BusinessAddSiteStatusFunctionalities() {}
Assuming this is just example code, it's about how you want to structure your project. You can easily split up all of your functions into different files and export them (MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).
Then, in the file(s) of your choosing, just use import (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import).
This is extremely common, and allows you to not pollute up your global scope. Just as easily, you could put a variety of helper functions in a file, and import specific functions of need into particular files. This way, you're not split between so many different files and you're still not polluting your global scope.
Unless you want to go through countless hoops, hard to read code and many headaches... You'll want to use a javascript framework like Angular in order to apply object oriented concepts to javascript without having to write ugly things like:
MyParentFunction.call(this);
Javascript frameworks like Angular allows you to use inheritance as you would in most object oriented languages.
class MyChildrenClass implements MyParentClass { }
If you absolutely want to do it using vanilla javascript, give this a read.

Haxe Javascript: Prevent '$bind' generation?

Is there a simple way to prevent $bind generation when passing around class member functions?
I have an object that takes in a function which will be called in an arbitrary interval. The object always binds itself as the 'this' binding before calling the function (this is done in the native side), therefore the call to $bind itself is unnecessary. However, I can't seem to find a simple way to prevent $bind from being emitted any time I grab a member function by value.
The only way I've found is to use __js__ with a string literal of the member function name, which I would rather avoid... Is there a typed way to do so? Or something a bit nicer? A way to still use haxe syntax w/ identifiers instead of a string literal?
Example:
private function onSpawn():Void
{
this.setAct( act ); // Will generate JS: this.setAct($bind(this,this.act));
// Id like to simply have it generate: this.setAct( this.act );
// Mitigated like this:
this.setAct( untyped __js__("this.act") );
}
private function act( dt:Float ):Void
{
...
}
Thank you.
You use macro to mask out the untyped expression, but this is quite dangerous.
Any reference to "this" will fail.
http://try-haxe.mrcdk.com/#70ee4
Btw, I think the compiler may be optimized to not generate $bind if the function code doesn't involve "this". You may want to raise an issue in the github repo about that.

What's this type of jquery coding style called?

I've always used jquery with a
$(document).ready(function {
....
});
But i've recently just inherited a complete site with the script file opening like the following:
var gc = gc || {};
gc.header = {
mobileNav: function () {
...
},
headerLink: function () {
...
}
};
gc.header.headerLink();
I've never seen it structured in this way - it's actually quite easy to use and would love to learn more about to help improve my coding styles.
If somebody could help me by providing me with what this type of coding style is? And - if you know of any, some learning resources?
Thanks in advance!
Lew.
It is usually referred to as namespacing. It has absolutely nothing to do with jQuery.
This style of JavaScript syntax is a little more object oriented. This makes it easier to edit and read but also helps your JavaScript stay 'clean' by namespacing your JavaScript. This means that you basically try to keep as much of your JavaScript out of the Global Object as possible - thereby reducing collisions in your code.
Line by line:
var gc = gc || {}; // If a 'gc' object exists, use it. Otherwise create an empty object.
gc.header = { // In the gc.header object create 2 methods, mobileNav and headerLink
mobileNav: function () {
...
},
headerLink: function () {
...
}
};
gc.header.headerLink(); // Reference the headerLink() method inside gc.header
This is far preferable to creating a more flat pattern where mobileNav and headerLink are global functions because mobileNav and headerLink are very generic functions that may be used and named identically in other plugins. By namespacing you reduce the risk of breaking your code and running into collisions because gc.header.headerLink() is much more unique.
It`s just ordinary JavaScript, it's a technique called namespacing: How do I declare a namespace in JavaScript?

How does javascript create an alternate syntax for objects such as function and array?

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.
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.

jQuery like custom functions

I have been wondering how I can create functions like jQuery. For example: $(ID).function()
Where ID is the id of an HTML element, $ is a function that return the document.getElementById reference of the element "ID" and function is a custom javascript function.
I'm creating a little library which implements some functions. And I want to use that sintax without using jQuery.
Now, my questions are: how I can implement that? What is the name of the tecnique that allow that?
Edit:
What I want to do is this:
HTMLElement.prototype.alertMe = function() {alert(this.value);}
Then, when I call document.getElementById('html_input_id').alertMe(), it must show an alertbox with the input value. But HTMLElement.prototype doesn't work in IE.
$ = function(id) {
return document.getElementById(id);
}
Okay, look, what you're asking has a lot of details and implications. The code for jQuery is open source, you can read it for the details; you'd do well to find a good Javascript book as well, the the O'Reilly Definitive Guide.
$ is just a character for names in JS, so as some of the other answers have shown, there's no reason you can't just write a function with that name:
var $ = function(args){...}
Since everyone and his brother uses that trick, you want to have a longer name as well, so you can mix things.
var EstebansLibrary = function(args){...}
var $ = EstebansLibrary; // make an alias
Since you end up doing different things with the entry point function, you need to know how JS uses arguments -- look up the arguments object.
You'll want to package this so that your internals don't pollute the namespace; you'll want some variant of the module pattern, which will make it something like
var EstebansLibrary = (function(){
// process the arguments object
// do stuff
return {
opname : implementation,...
}
})();
And you'll eventually want to be prepared for inheritance and that means putting those functions into the prototype object.
You can use prototype to assign a new function to the Element prototype.
Element.prototype.testFunction=function(str){alert(str)};
This would provide the function 'testFunction' to all HTML elements.
You can extend any base Object this way, i.e. Array, String etc.
This will work without any plugin at all - although that said I don't think it will work in IE. I believe libraries such as MooTools and jQquery create their own inheritance with DOM elements to ensure cross-browser compatibility, although don't quote me on that.

Categories

Resources