JavaScript anonymous function syntax - javascript

The following syntax is present in a .js file.
var fun1 = function(fun1_parameter1){
return{
fun2 : function(){
alert("xxx");
}
}
}
I am not getting this at all.
This js file uses namespaces also.
Help me understanding this.

What that code does is define a single variable named fun1.
The value is an anonymous function with one parameter.
Calling the function would return an anonymous object with a .fun2 property, which points to another anonymous function.
Calling that function would trigger the alert:
fun1(0).fun2(); // triggers alert("xxx")

Related

How can I set javascript function in global?

I want to set my function in global js. So it can called from anywhere
I have function this :
$(function () {
function formatCurrency(input) {
return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
}
});
I put the function on the
C:\xampp\htdocs\mysystem\resources\assets\js\main.js
And I add this : <script src="{{URL::asset('/resources/assets/js/main.js')}}"></script> on the
C:\xampp\htdocs\mysystem\resources\views\layouts\app.blade
When executed, on the console exist error like this :
GET http://mysystem.dev/resources/assets/js/main.js 404 (Not Found)
How can I solve it?
The issue seems to be you're using asset() wrong.
asset refers to a file in /public.
You should compile/minimize your JS for production and put it somewhere in /public, i.e. /public/js/my.js
You should define you function as a method of the window object.
window.formatCurrency = function(input) {
return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
}
Another more clean way it would be to define your function as a method of an object called Utils, like below:
var Utils = (function(){
function formatCurrency(input){
return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
}
return {
formatCurrency: formatCurrency
}
}());
Doing so, you will not pollute the global namespace. You will have only one variable defined in the global namespace called Util, which would contain an obejct with useful functions that can be used by other parts of your application. As it is you can't see the benefits of the latter approach. However you can consider how it would be if you wanted to use 3 more functions, that by their own use 2 other functions as helpers. If that was the case your return statement would also contained the 3 more functions, whereas the 2 functions I mentioned before wouldn't be epxosed at all !
You can define global function like this
window.formatCurrency = function(input){
return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
}
and you are define function in ready function($(function)) then you must call this in ready function also. So better define it outside of ready function or in self invoking function.

How can you pass anonymous functions as parameters to existing functions to use later in javascript?

I am trying to create a basic javascript framework that you can pass different things into, including functions for it to execute later. Right now, I'm in a more simple testing phase, but I can't quite get the function calling to work. A piece of my code is here:
[My JS Fiddle][1]http://jsfiddle.net/mp243wm6/
My code has an object that holds different data, and I want to call the method later, but with data that is available at the time of creation. Here is a code snippet of the function that uses the function that is passed to the object:
clickMe : function() {
this.obj.click(function() {
this.func();
});
}
Any suggestions or things I should read are welcome.
The problem is that there're two different contexts:
clickMe : function() {
// here is one
this.obj.click(function() {
// here is another
this.func();
});
}
You can simple pass the function as parameter, like the following:
clickMe : function() {
this.obj.click($.proxy(this.func, this));
}
http://jsfiddle.net/mp243wm6/2/
The problem:
Considering your code in the JSFiddle, you have:
onClick : function() {
this.obj.click(function() {
this.func();
});
},
As noted, you have different contexts going on here.
Consider the snippet this.obj.click(function() { this.func(); }). The first this here is a reference to the framework.events object. The second this here is a reference to whatever will be this when this function get called. In the case of your JSFiddle, when this.func gets called, this is actually the DOM object that represents the <div id="test">TEST</div> node. Since it doesn't have a func function, calling func() on it causes:
Uncaught TypeError: undefined is not a function
You have to understand the following: you have to pass the correct this in which you want the function func to be called.
The solution:
A couple of ways to make it work as you would like:
1. with bind
this.obj.click(this.func.bind(this));
This way, you are telling: "call my this.func function, but make sure that it will be called using the this that I am passing as a parameter". Vanilla JS, no $.proxy stuff.
JSFiddle
2. with a copy of the reference to the actual function
onClick : function() {
var theFunctionReference = this.func;
this.obj.click(function() {
theFunctionReference();
});
},
This way, you will not rely on the value of this outside of the context of the framework.events object.
JSFiddle
The issue is that this is not bound to the correct object. I would suggest you look into Function.bind() because that creates a function with this pointing to the right thing.

JavaScript: why cannot I not call parentFunc.parentFunction() from the callee without the 'this' keyword?

So I was getting the following error:
TypeError: parentRef.parentFunction() is not a function
in my callee.
My callee looked sort of like this
function callee(parentRef){
function subRoutine(){
//stuff
parentRef.parentFunction(params);
}
}
And the caller looked like this:
function caller(){
refToCallee = new callee(this);
refToCallee.subRoutine();
parentFunction(prms){
//other stuff
}
}
Then I realized that I had seen code that changed the caller to have the following line when defining parentFunction
this.parentFunction = function(){ etc.}
What is the thiskeyword doing here. Is it a namespacing thing? More specifically why does my first definition without using the this.funcName syntax not work?
When you define a function like parentFunction inside another function like caller, there are 3 ways of doing it.
function parentFunction() { ... }
var parentFunction = function() { ... };
this.parentFunction = function() { ... };
The first declares a function inside the scope of caller. It is only usable inside caller.
The second declares a local variable that happens to be a function, it is also only callable inside caller.
The third declares a property on the caller object that happens to be a function. Anyone with a reference to a caller object (like in your example) can call it. This is why the this.parentFunction is needed for callee to be able to use it.
What you have in your original example,
parentFunction(prms) { ... }
is not proper javascript. It does not declare a variable or a function, nor does it execute any code.
It appears you want a callback like this:
function callee(callback){
//stuff
callback(params);
}
function caller(){
callee(callback);
function callback(prms){
//other stuff
}
}

Javascript syntax confusion [beginner]?

I don't understand what view("") does in the following javascript method that is part of Model object:
addView: function(view) {
this.views.push(view);
view("");
}
view(object) method is not defined anywhere...
view(object) method is not defined anywhere
The function that view is referring to is passed as argument to addView. This is also called a callback. A callback is a function (A) that is passed to another function (B) and is supposed to be called by that function (B).
So somewhere, there might be code that looks like
obj.addView(function(v) {
// using anonymous function expressions is a pretty common way to define
// callbacks
});
or
function someFunctionName(v) {
// any function will do, no matter how it is defined
}
obj.addView(someFunctionName);
Functions are first class objects in JavaScript and can be passed around like any other values.
It looks like it's passing in a function called view. Then it calls the view function.
Functions are first class citizens in JavaScript and can be passed as parameters to other functions.
addView: function(view) {//view is a function itself that is passed into the current function.
this.views.push(view);
view("");
}
The call could be like this
someObj.addView(function(par1){alert("I am a function too")});
Assume you have function view , if you call the view function without passing parameter in view(), then it returns like undefined, In such case we need to initialise the passing parameter value from function view("")
function view(passedData){
alert (passedData);
}

How does browser read the JavaScripts, which should come first (set on the top):event? function? or sub function

A simple question.
I have a web project includes multi JavaScripts.
JS:
// (1) Event
$('.input').keyup(function()
{
keyUpFunction();
});
// (2) Function
function keyUpFunction(){ ... }
(1),(2) which should come first in one javascript file? If the browser read the function first, does it store the function in memory and invoke it when scan the event.
In some case, the same function is defined in multi javascript . e.g.
prm.add_endRequest(function() {
fn1();
fn2();
});
$(document).ready(.......)
Should I duplicate the function name and define each component in each js file.
or keep the function declare in one file and invoke sub-function composite the function?
Functions defined in the following manner:
function fooBar(){}
Are 'hoisted' to the top of the current scope. This means they will always be available, in the current scope, even if they are defined at the end of the file.
This does not hold true if you defined you functions like this:
var fooBar = function(){};
These functions are not hoisted, and must be defined before they can be used.
It should be noted that in your specific example, keyUpFunction will only be called once a keyup event has fired. This also means that all javascript on your page will already be evaluated, so the keyUpFunction will be defined (parsed) already regardless.
EDIT: To be more explicit, this first example is okay:
doSomething('hello world');
function doSomething(str){
console.log(str);
}
However, this will cause you problems:
doSomething('hello world');
var doSomething = function(str){
console.log(str);
}
#Matt's answer covers the function hoisting stuff nicely.
To avoid function name clashes within multiple files, wrap your content in an immediately invoked function expression, e.g.:
(function() {
// put your variables functions here
...
// register event handlers
})();
Any variables or functions declared therein will be constrained to that scope.

Categories

Resources