Does Coffee Script allow using Javascript libraries? - javascript

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

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/

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.

Obfuscate javascript properties?

I've recently tested UglifyJS and YUI Compressor and noticed something odd.
Both minifiers don't seem to change the names of object properties, only the names of variables and functions.
for instance if I have the following code:
var objName = {first:2, second:4};
alert(objName.first + " " + objName.second);
the names first and second remain unchanged in the minified version.
Why is that?
Since in javascript a new scope is created in a function, you can scope your code in an immediately invoked function.
// scoped
(function() {
var objName = {first:2, second:4};
alert(objName.first + " " + objName.second);
})();
Then using Google's Closure Compiler, if you turn on the "Advanced" optimization it will see that the properties are only used locally, and will obfuscate them.
// result
var a={a:2,b:4};alert(a.a+" "+a.b);
It's because it doesn't know where the object is going to be used. It could be used externally by other code and you wouldn't want your other code to have to change whenever you obfuscate it.
Edit So basically, it's like that to prevent obfuscation from breaking external/internal references to properties that may not be possible to figure out while obfuscating.
Since there are no well defined scoping rules around objects in JavaScript it's impossible to obfuscate the names in a way that is guaranteed to be correct.
For example, if you had the following function:
function f() {
return { first: 'foo', second: 'bar' };
}
In order to obfuscate the property names you would have to nail down all the places that f is called from. Since functions are first-class in JavaScript they can be assigned and passed around in arbitrary ways making it impossible to pin down where f is referenced without actually running the program.
Additionally, JavaScript doesn't have any way for you to specify intent around what's public API and what isn't. Even if the minimizer could reliably determine where the function is called from in the code you give it, there would be no way for it to make the same changes to code that it hasn't seen.
I guess that's because the minifiers would break the object properties. Consider this:
function getProp(ob,name) {
return ob[name];
}
var objName = {first: 2, second: 4};
var prop = getProp(objName, "second");
There's no way for the minifier to know the string literal "second" being an object property. The minified code could look like this then:
function a(b,c){return b[c]}var d={p1:2,p2:4};var e=a(d,"second")
Broken now.
The latest release of uglify (today) has object property mangling, see v2.4.19. It also supports reserved files for excluding both object properties and variables that you don't want mangled. Check it out.
The only public tool so far to obfuscate property and function names (afaik) is the Closure Compiler's Advanced mode. There are a lot of limitations and restrictions, but the end result is generally worth it.
As a passing note: the Dojo Toolkit is compatible (with some minor modifications) with the Closure Compiler in Advanced mode -- arguably the only large-scale public JavaScript library that can be fully obfuscated. So if you are looking at obfuscation to protect your IP, you should look into using Dojo for the task.
http://dojo-toolkit.33424.n3.nabble.com/file/n2636749/Using_the_Dojo_Toolkit_with_the_Closure_Compiler.pdf?by-user=t
Stephen
What about doing something like:
// scoped
(function() {
var objName = {first:2, second:4};
var vA = 'first';
var vB = 'second';
alert(objName[vA] + " " + objName[vB]);
})();
Once objName.first and/or objName.second are referenced enough times, this technique will start to save characters. I can't think of any reason that wouldn't work, but I can't find any minifiers that do it.

λ and function 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.

Categories