assign a copy of a function to a var - javascript

Is it possible to define a function and then assign copies of the function to different vars?
This is essentially how far I've got...
function add(x, y){
return x + y;
}
var function1 = new add()
var function2 = new add()
This doesn't seem to work as it's trying to run the add function each time. The same goes for
var function1 = new function add()
Do I need to be using prototype in some way or am I looking at it in the wrong way?

This should do the trick
var function1 = add;
var function2 = add;

You are evaluating the function. To assign the function itself to a variable, use
var function1 = add;
var function2 = add;
However, it's not quite clear why you want to copy the function.

if your just trying to create references to the function just make this modification
function add(x, y){
return x + y;
}
var function1 = add;
var function2 = add;
After which you are able to call the functions like this.
function1(10,11);
function2(1,2);

A function in Javascript is an object as any other.
You can create many references to the same function and store them for example in an array
function add(x, y) {
return x + y;
}
var v = [add, add, add, add];
alert(v[3](33, 9)); // Will show 42
The only "magic" thing happens when you call a function getting it from an object member lookup
x = {};
x.f = add;
x.f(12, 3); // Returns 15
the "strange" thing that will happen is that this inside the function when called that way will be the object, and not the global window object as it happens when you call a function directly.
This also means that, confusingly enough,
x.f(z);
is not the same as
[x.f][0](z);
or as
var ff = x.f;
ff(z);
because in the first case this will be x, in the second case this will be the array instead and in the third case it will be the global window object.

Related

Javascript immediate function and code scope

I am confused about scope when comparing normal function and immediate function.
Here is a example:
var num=5;
var x=3;
doubleNum = function(){
num = num*x
x++;
return num;
};
console.log(doubleNum());//15
console.log(doubleNum());//60
console.log(doubleNum());//300
This is a normal function that num and x are defined globally and accessible by doubleNum, as a result num and x are updated.
var num=5;
var x=3;
doubleNum = function(){
num = num*x
x++;
return num;
}();
console.log(doubleNum);//15
console.log(doubleNum);//15
console.log(doubleNum);//15
However if I define a immediate function and call it same way as above, I got different answer. Even I am expecting to have same output
Did I miss something essential? Or did I understand some concept wrong?
Please help.
Thanks in advance.
Jsfiddle
Because your doubleNum is not a reference to the function, but keeps the result of an anonymous function call.
In the first case you assign to the doubleNum a function and every time calling it via doubleNum(), you change the outscoped variables inside it and return a num. You do this 3 times. Your code is equivalent something to like
var num=5;
var x=3;
doubleNum = function(){
num = num*x; // Every call will affect the outscoped num
x++; // Every call will affect the outscoped x
return num;
};
var val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
In the second case you assign to the doubleNum the result of a single call anonymous function. The function value is already computed one time and assigns the result to the doubleNum. Your code is equivalent something to
var num=5;
var x=3;
var doubleNum;
var myFunction = function(){
num = num*x;
x++;
return num;
};
doubleNum = myFunction(); // Only one call
console.log(doubleNum);
console.log(doubleNum);
console.log(doubleNum);
Did I miss something essential?
Just that in the second case, the value of doubleNum is already computed because the function is invoked as soon as it is defined.
On the other hand, in the first case only function definition was assigned to doubleNum rather than the result of its invocation.
The immediate function call is being evaluated only once. You're allocating a value not an immediate function to doubleNum. To accomplish a similar effect, try using a class and getters.
class ClassName {
constructor(){
this.num = 5;
this.x = 3;
}
get doubleNum() {
this.num = this.num*this.x++;
return this.num;
}
}
var double = new ClassName();
console.log(double.doubleNum);//15
console.log(double.doubleNum);//30
console.log(double.doubleNum);//300

How can I assign a function to an element using JavaScript?

I want something like this:
div.onclick = function(x, y);
How can I do this without executing the function?
I don't want to use jQuery.
Putting () after the function will call it. So don't do that.
div.onclick = function; // Note: function is a keyword and can't really be used as a variable name
That won't call the function with the arguments you want though. Event handler functions are always called with one argument: the event object.
You need to create a new function to call yours with those arguments.
function myhandler(event) {
function(x, y); // Still not a valid name
}
div.onclick = myhandler;
var NewFunction = function(x){
// your function code
};
div.onclick = NewFunction;
var myFunction = function(x,y){
//Some code here
};
div.onclick = function(){ return myFunction(x, y); }
In the second function assignment you ofcourse should replace x and y with something known to that context.

Confusing function in javascript functional programming

I'm new to functional programming and I'm trying to learn it in javascript. I found some examples and wrote my own snippet, but I don't understand WHY it works. There is a function called whatTheHeckIsThis. Can someone tell me what it is doing or what its purpose is? Note that when running this code, the output is true.
function boolFlipper(someFn){
return function whatTheHeckIsThis(x,y){
return !someFn(x,y);
};
}
var checkStrings = function(x, y){
return x === y;
}
var flipperTester = boolFlipper(checkStrings);
var str1 = "this string";
var str2 = "that string";
console.log(flipperTester(str1, str2));
My confusion is why can't I just do this instead:
function boolFlipper(someFn){
return !someFn(x,y);
}
a reference to whatTheHeckIsthis() will be returned and stored into flipperTester
After this, flipperTester can be used like a function.
You can use this language feature to abstract some code.
Simple example:
function addTen(x) { return x + 10 }
function multiplyByTen(x) { return x * 10 }
...
var doMath
// somewhere a user selected something
if (userInputSaysAdd) doMath = addTen
if (userInputSaysMultiply) doMath = multiplyByTen
// this will be the choosen function
doMath(someValue)
Your second version doesn't work for 2 reasons:
The purpose of boolFlipper is to return a new function, which you can assign to another variable and later call.
Your function doesn't have x and y parameters.
To solve #2 you could write:
function boolFlipper(someFn, x, y) {
return !someFn(x, y);
}
You would then have to call it like:
console.log(boolFlipper(checkStrings, str1, str2));
But you still couldn't do:
flipperTester = boolFlipper(checkStrings);
The original snippet returns a closure, which is bound in the environment where someFn is equal to the function passed as an argument to bookFlipper(). You can then assign this function to a variable, and call it with new arguments, that are assigned to x and y, and then the the function saved in someFn() is called, the return value is negated with !, and this is returned.
For more information about closures, see How do JavaScript closures work?
In JavaScript functions are objects, so you can return them. When you return a function you are getting a function object, so you can call it as any other function. For example:
function myFun() {
return function() {
console.log("test");
};
}
var functionInside = myFun();
/* This is like doing:
var functionInside = function() {
console.log("test");
};
*/
functionInside(); // This will execute the function.
Example with your code:
This variable:
var flipperTester = boolFlipper(checkStrings);
contains a function like this:
var flipperTester = function (x,y) {
return !someFn(x,y);
}
And this is something similar to
function flipperTester(x,y) {
return !someFn(x,y);
}
So when you do:
flipperTester(str1, str2)
You are executing that function. The variable "someFn" inside there is the function "checkStrings", because you passed it when you initialize flipperTester variable.
boolFlipper is, for our purposes here, a function decorator: it takes a function and modifies it to do something else. A more instructive example might be a logging function:
var alsoLogs = f => (...args) => {
var result = f(...args);
console.log(result);
return result;
};
// now we have a function that adds 2 numbers:
var add = function add(a, b) { return a + b; };
// and we want to also log the result
var addAndLog = alsoLogs(add); // addAndLog is a function, would be the whatTheHeckIsThis from your example
addAndLog(2, 3); // logs 5 to the console
If you don't understand all the ES6 syntax that's ok, just understand that alsoLogs take a function f and returns a function that does the exact same thing as f but also logs the result to the console.
Since we as programmers are lazy, we don't want to have to write functions to glue together other functions every time we want to do this, so we write a function to do it for us, compose.
So now we can just say something like:
var addAndLog = R.compose(console.log, add);
addAndLog(2, 3); // logs 5 to the console

Class instance that returns a function

I was just playing with JavaScript and creating constructors, and I came across this perplexing code.
var foo = function(){
this.x = 1;
return function(){
return this.x;
}
}
var x = new foo();
console.log(x);
I executed the following for this:
console.log(x); // The given output is expected for this line of code
console.log(x());
console.log(x()());
console.log(x()()());
All of the above gave me the same output as following:
function (){
return this.x;
}
Can somebody explain what is happening in the above code.
I could not give a proper title for this question. Sorry about that.
Note: I'm aware of constructors in JS. And the above code was just out of curiosity.
To make a long story short - it's not doing anything useful.
If a constructor returns an object, then the value produced by the new expression is that value rather than the constructed object. So instead of getting an instance of foo, you are getting a function that returns this.x.
It looks like this code is trying to produce a function that returns the this.x value of the created object, but that's not what it's doing. Since you are calling x() by itself, this.x is actually referring to the global x variable, so no matter how many times you call x()()(), it just returns itself.
If you used any variable name other than x and did not create an x variable (e.g. y), then y() would just return undefined, and y()() would produce a ReferenceError.
This would also fail much sooner in strict mode, becuase this inside the function would be referring to undefined when you tried to call it.
My interpretation is this:
x contains the result of calling foo().
foo() returns a function:
function(){
return this.x;
}
the body of this function is written to the console
Here is an example to the previous answer, that demonstrates it:
var x = 5;
var foo = function(){
this.x = 1;
return function(){
return this.x;
}
}
var b = new foo();
b() //--> 5
This code is all about function invocation context.
At runtime, the this referenced in this.x = 1; is bound to a different object than the this referenced in return this.x;
x() invokes the anonymous function returned by foo, in a global context. For ECMAScript 3 (and earlier) environment, global context function invocation binds the global object to this, inside the invoked function. Thus, return this.x; refers to var x you define on the global object.
In ECMAScript 5, use strict; statement can be placed in any function declaration to disable the binding of the global object in "this" way.
The anonymous, nested function can access "foo's" this in a closure:
var foo = function(){
this.x = 1;
var that = this;
return function(){
return that.x;
}
}
var x = new foo();
console.log(x); // function(){ ...
x(); // 1

Is it possible to access private variable of javascript function

Suppose I have a JavaScript function. and it contain a variable x;
function A(){
var x = 12+34;
}
Is it possible to access x from outside function x?
No, the ability to do so would not make any sense. Suppose we changed your function slightly and called it 3 times:
function x(n){
var x = n+34;
}
x(1), x(2), x(3);
At this point, the function has run 3 times, so the variable x has been created 3 times — which x would you expect to be able to access? Then there's garbage collection; how could references and data be cleared from memory if the browser had to keep variables alive once they're no longer in scope?
If you want to, you can do something like this:
function x() {
x.x = 12+34;
}
x();
or, if the variable will be static/constant as you have it
function x() { }
x.x = 12+34;
or finally, as others have pointed out, by declaring x under a different name outside of the function's scope:
var y;
function x() {
y = 12+34;
}
x();
You can not access it directly by its name, try removing 'var' from the variable declaration, as this should make the variables globals, or placing them outside the ready function. and return the value of x from the function.
You can do some thing like this:
$(document).ready(function() {
var x;
function x(){
x = 12+34;
return x;
}
alert(x());
});
Here is its jsfiddle
Hope this helps.
Yes, but not as scoped in your example above. You must use closure. Consider the following:
var x,
A = function () {
x = 12 + 34;
};
In this manner you can access x from inside the function A. What is even better is that x has direct access to the private members of A and so can be used to leak private data outside of A.

Categories

Resources