λ and function javascript - javascript

is there any way to map the λ key to the function keyword?
so that these work:
var rFalse = λ() {
return false;
}
(λ(){
var str = "i'm in a closure";
}());
window.onload = λ() {
alert('window loaded');
}
I know that they are attempting to put a shortened function keyword in ecmascript v6, but I'm wondering if it is possible to do it now.

JavaScript does not offer aliasing of keywords, so it is not possible make the syntax you're trying to use valid.

It is possible, just not natively. You'd have to look into implementing or using an existing DSL.
A good example could be CoffeeScript, which includes an Extras script for running on client-side via:
<script type="text/coffeescript">
Their contents are converted to and reinserted into the document as JavaScript by:
<script src="extras/coffee-script.js"></script>
However, keep in mind that client-side DSLs risk drastically increasing load times and ruining the user experience -- CoffeeScript is primarily server-side for a reason.

I wouldn't think so, since function is a keyword... You'll have hard time passing your program through the parser.

Related

JavaScript module pattern with example [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I can't find any accessible examples showing how two (or more) different modules are connected to work together.
So, I'd like to ask whether anyone has time to write an example explaining how modules work together.
In order to approach to Modular design pattern, you need to understand these concept first:
Immediately-Invoked Function Expression (IIFE):
(function() {
// Your code goes here
}());
There are two ways you can use the functions. 1. Function declaration 2. Function expression.
Here are using function expression.
What is namespace?
Now if we add the namespace to the above piece of code then
var anoyn = (function() {
}());
What is closure in JS?
It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.
var scope = "I am global";
function whatismyscope() {
var scope = "I am just a local";
function func() {return scope;}
return func;
}
whatismyscope()()
Now we will apply these three concepts I mentioned above to define our first modular design pattern:
var modularpattern = (function() {
// your module code goes here
var sum = 0 ;
return {
add:function() {
sum = sum + 1;
return sum;
},
reset:function() {
return sum = 0;
}
}
}());
alert(modularpattern.add()); // alerts: 1
alert(modularpattern.add()); // alerts: 2
alert(modularpattern.reset()); // alerts: 0
jsfiddle for the code above.
The objective is to hide the variable accessibility from the outside world.
I would really recommend anyone entering this subject to read Addy Osmani's free book:
"Learning JavaScript Design Patterns".
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.
I come from a c# background so have added some terminology I find useful from there.
Html
You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).
You need add files to the project with script tags like this:
<script type="text/javascript" src="app/native/MasterFile.js" /></script>
<script type="text/javascript" src="app/native/SomeComponent.js" /></script>
It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!
Namespace file
MasterFile.js
myAppNamespace = {};
that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).
Module(s)
SomeComponent.js
myAppNamespace.messageCounter= (function(){
var privateState = 0;
var incrementCount = function () {
privateState += 1;
};
return function (message) {
incrementCount();
//TODO something with the message!
}
})();
What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.
Concepts
I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.
I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.
You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.
Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/

Does Coffee Script allow using Javascript libraries?

It looks like Google's Dart language doesn't allow you to call native js functions (say, using jQuery or my existing .js code).
Does CoffeeScript allow any of the above?
yes you can use any javascript library with coffescript, just include the lib the usual way and write your code in the coffeescript 'style', so for a jquery example:
$(function () {
$('.something').on('click', function () {
console.log('you clicked me');
});
});
becomes
$ ->
$(".button").on "click", ->
console.log('you clicked me');
A quick google found some ineresting blog's on the subject, coffeescript & jquery fun and using jquery with coffeescript.
There is also a pragmantic programmer book with a chapter focused on using jquery and backbone in coffeescript applications
n.b. as pointed out, remember that the coffeescript 'compiler' wont check that functions exist, only that the syntax is correct
You can use jQuery and native JavaScript functions. You simply need to write them in the correct CoffeeScript syntax.
Bear in mind that CoffeeScript is a source to source compiler. It will transpile CoffeeScript to JavaScript. It won't know whether any specified functions exist.
So if you wrote this CoffeeScript, it would compile just fine:
words = ["hello", "world"]
alert word.touppercase() for word in words
Note that touppercase() is undefined in JavaScript. It should be toUpperCase(). Nonetheless, CoffeeScript will output:
var word, words, _i, _len;
words = ["hello", "world"];
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
alert(word.touppercase());
}
You would then run into the error as a JavaScript error once you ran this in your browser, not a CoffeeScript error. You can use the "Try CoffeeScript" link on CoffeeScript site to see how the translation takes place and try to run it. You can also try it in jsFiddle by changing the Panels option to use CoffeeScript instead of JavaScript.
CoffeeScript is JavaScript.
Or rather, more precisely, CoffeeScript's only purpose is to make writing JavaScript an easier, 'cleaner' experience. All the CoffeeScript code you write is compiled into Javascript.
The CoffeeScript compiler only checks your code's syntax. It never bothers to check and see if the variables and functions you're referencing actually exist (this would be impossible to do with running the file anyway). So you can certainly call 'native' JavaScript functions with your CoffeeScript code but that's simple because they come out the other side as simple JavaScript function calls.
You are also able to use javascript within your coffeescript. All you have to do is use back-ticks:
hello = `function() {console.log("hello")}`
However, there is almost never a good reason to do this. Although there is one scenario where this is useful and that is reusing the same variable name in nested functions.
For example:
parent = ->
outer = 2
changeOuter = ->
`var outer` ##scopes outer to changeOuter
outer = 1
changeOuter()
return outer ##returns 2 but would have returned 1
##if we did not re-scope the varibale

Any way to add code to every function call

I'd like a quick way to add something like
console.log(functionName)
to the top of every function.
Is there a quick and easy way to do this, or would I need to manually add that code to every function.
You could try something like this:
for( var x in window) {
if( typeof window[x] == "function") {
(function(x) {
var ox = window[x];
window[x] = function() {
console.log(x);
ox.apply(null,arguments);
};
})(x);
}
}
However, this would only work on global functions, not functions of objects or scoped functions. It's also kind of a nuke, so is a poor substitute for manually adding console logging to the specific functions you want to call.
Instead it would probably be better to insert a breakpoint in the code (using the browser's developer tools) and checking the call stack at that point.
I'm afraid that this is not possible with JavaScript as it doesn't support runtime modification of function contents.
You could, however, make a backup of your scripts and do a search & replace to save some time on the editing part; modern editors support basic regular expressions to help you out.
If you use a flow control library like Frame.js the you have a low level access to the most important functions in your application. Of course you would have to build the application with Frame from the beginning. This won't work if you are trying to modify an already built application.

How to detect variable dependencies for a javascript function

Say I have this function:
function test(){
return a + b + 1;
}
How can I dynamically figure out that it will require globals a and b to be able to run? E.g. something like get_dependencies(test) returns ['a', 'b']
There's no built-in way to do that in standard JavaScript, if you're trying to do it with JavaScript itself.
On nearly all (but not all) JavaScript engines, you can get a form of the source of a function from the function object's toString function, e.g.:
var testSource = test.toString();
...and then of course you could parse that. This is non-standard behavior (the result of calling toString on a function is not defined in the specification), but it's widely-supported. You'd still have to do the parsing to find the symbols.
For the parsing, you have a couple of options. You could try to separate the parser portion of JSLint out of the rest of it, or alternately the terribly-named UglifyJS compressor has a full JavaScript parser which is already separate from the compressor part (see parse-js.js; apparently there's a tiny bit of NodeJS-specific stuff you might want to remove).
You can use a Javascript 'lint' tool that will test your code for common mistakes or oddities.
Some can be found online:
http://www.jslint.com/
http://www.javascriptlint.com/online_lint.php (can also be downloaded)
In your case, you might want to isolate individual functions via a regular expression for example, and submit them to such a tool.

storing document in a variable

I just wondered if I stored document into a variable whether there would be a speed enhancement so if I had
var doc= document;
myElement = doc.getElementById('somethingSweet');
I know in this example it wouldn't make that much different but my thinking is that my variable would act as a "pointer" to document and so m scripts would not need to try and refer back to document.
There is value in storing something that will be reused in a variable. Document is a poor choice since it's already available on the window. Typically, you would store things that you look up in the document, that aren't already available via top-level properties. This is especially true in functions or plugins that you may develop where you want to keep a reference to the DOM elements that the plugin is operating on handy to avoid looking it up each time.
Document is a global object. How can it be faster to refer to another variable and then to document instead of directly to document? That's a retorical question :)
Wrap your code in a self-executing anonymous function, and pass document as a variable
(function(doc) {
//code
})(document);
By itself, I don't see any improvements it can make. However, this is a widely used minification technique; minified, doc turns into something like a, so whenever your code uses for example doc.getElementsByTagName, it turns into a.getElementsByTagName.
Edit: A quick example.
//Before minifying
(function(document) {
var anchor = document.createElement('a');
anchor.id = 'world';
document.body.appendChild(anchor);
document.getElementById('world').innerText = 'Hello World';
})(document);
//After minifying
(function(a){var b=a.createElement("a");b.id="world";a.body.appendChild(b);a.getElementById("world").innerText="Hello World"})(document);
Notice how document turned into "a", and so we saved 7 characters each time! Note that writing obfuscated code isn't suggested, and you should only minify right before shipping out the code.
Minified using the excellent Closure Compiler

Categories