This question already has answers here:
how do I compare 2 functions in javascript
(6 answers)
Closed 6 years ago.
I need to detect whether two anonymous functions are the same.
In the console, why does the following line return false?
(function() { alert("hello"); }) === (function() { alert("hello"); })
Is there a comparison operator or other method to identify that these are 'functionally' the same?
EDIT:
People are asking for the use of this.
It's for removing a function that has been previously pushed into an array of functions. See http://jsfiddle.net/w6s7J/ for a simplified test.
There is no real way to compare 2 different anonymous functions for 'functionality'.
You can check if they are the same object by using your example code.
var func = function () {
alert('hello');
};
alert(func === func);
The above will work, as you are checking to see that both objects are the same.
The only other method for comparing is to compare them as a string.
var func1 = function () {
alert("hello");
};
var func2 = function () {
alert('hello');
};
alert(func1.toString() === func2.toString());
Oops!, they are functionally the same, the difference is the quotes used, So this returns false.
(function() { alert("hello"); }) === (function() { alert("hello"); })
Returns false because they are different objects in javascript.
(function() { alert("hello"); }).toString() === (function() { alert("hello"); }).toString()
Returns true because they are the same strings.
Also function objects have a name property which return the name of the function (but it does not work in IE):
var a = function b() {}
alert(a.name);//write b
Related
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 2 years ago.
Can anyone tell me what I can replace the evil eval with in this code?
var x = function(funcName) {
function funcA () {
console.log("a");
}
function funcB () {
console.log("b");
}
var funcToRun = eval(funcName);
return funcToRun();
};
x("funcA");
x("funcB");
I've see a bunch of different solutions, but none seem to fit this scenario. Essentially, I need to be able to pass a string into a function as a "config" of which sub-function to run. I don't have access to the code that calls x, I've just been instructed that only primitive and string values can be configured in the call.
P.S. This is a super simplified version of the actual function.
Thanks!
James
You could just create an object and add those functions as properties that you can then access with a string.
var x = function(funcName) {
function funcA() {
console.log("a");
}
function funcB() {
console.log("b");
}
const fs = {
funcA,
funcB
}
var funcToRun = fs[funcName]
return funcToRun();
};
x("funcA");
x("funcB");
I'm stuck with this problem. Need to check if the 2 functions are the same or refer to the same.
So the scenario is kind of like this :
fn1 function are anonymous.
function fnName(args) {
if(this.fn1 === this.json1.fn1)
//this is true
else
//this is false
}
here both this.fn1 and this.json1.fn1 points to the same function definition. Is there a way to find out if they are pointing the same or not ?
I have tried using function.toString() but this gives the same output for any function i.e;
function() { [native code] }
and on this being compared it gives true as the output for any 2 function that are not even same.
On comparing === It's not considering them as same. On debugging it shows that it is pointing to the function at the same line.
On doing Object.is(this.fn1,this.json1.fn1); is returning false , which means they are not the same object.
How these functions are set to the attribute are through using the bind function such as :
fn1 = fn1.bind(this);
json1["fn1"] = fn1.bind(this)
So now we know these are 2 different Objects
Functions are objects in JavaScript. Even two functions that are written exactly the same are still two distinct objects in memory and will never be equal.
All you can do is convert the functions to strings and compare the strings. I would guess though that you didn't actually invoke the .toString() function during your comparison expression and instead compared the actual .toString function code.
var o1 = {
foo: function (message){
console.log(message);
}
};
var o2 = {
log: function (message){
console.log(message);
}
};
var o3 = {
log: function (msg){
console.log(msg);
}
};
var test = o1.foo;
function compare(f1, f2){
// You must convert the functions to strings and compare those:
console.log(f1.toString() === f2.toString());
}
compare(o1.foo, o2.log); // true - the two functions are identical
compare(o1.foo, o3.log); // false - the two functions are not identical
compare(o1.foo, test); // true - the two variables reference the same one function
// This is just to show how not properly calling toString() affects the results:
console.log(o1.foo.toString); // function toString() { [native code] }
console.log(o1.foo.toString()); // function (message){ console.log(message); }
Consider the example below:
var fun1 = function() { console.log('fun1') };
var fun2 = fun1;
var fun3 = fun1.bind({});
console.log(fun1 === fun2); // true
console.log(fun1 === fun3); // false
function test() {
fun1 = () => { console.log('new function') }
fun1();
fun2();
fun3();
console.log(fun1 === fun2); // false
}
fun1();
fun2();
fun3();
test();
fun3 is a copy of fun1, it returns false in comparision.
fun2 and fun1 are the reference to the same function.
Inside, test() function, assign fun1 to a new function. However, fun2 is still pointing to the old function, so it returns false when comparing them.
So, it is safe to compare 2 references of functions using ===.
This question already has answers here:
What do parentheses surrounding an object/function/class declaration mean? [duplicate]
(7 answers)
Closed 8 years ago.
I consider myself a pretty strong javascript coder and am familiar with most all of the javascript syntax. But have been puzzled by the following syntax:
function() {
return function() {
}
} ();
Can someone explain what the parenthesis at the end is supposed to be used for?
So, the expression:
(function() {
return function() {
}
})
Evaluates to a function (without a name in this case) that returns some other function.
Adding ():
(function() {
return function() {
}
})();
Would simply call that function.
Another way to write this would be:
var foo = function() {
return function() {
}
};
foo();
It is a self invoking function. Meaning a function that declares and calls itself.
Another form would be:
(function() {
return function() {
}
}());
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
var f1 = function() {
console.log('bar');
};
And you could subsequently call it like so:
f1();
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions: incrementCounter and resetCounter. You can call them like so: testModule.incrementCounter() and testModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
The anonymous function is executed and the return value is assigned to the variable.
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I'm trying to read the Prototype source. I've come to this part.(Unfortunately, this snippet is in the beginnning).
What does this () mean?
Browser: (function(){
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
IE: !!window.attachEvent && !isOpera,
Opera: isOpera,
WebKit: ua.indexOf('AppleWebKit/') > -1,
Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile.*Safari/.test(ua)
}
})(),
I am referring to the last line before the comma?
The code is defining an anonymous function (the (function (){ ... }) bit) and then calling it (with no arguments). It then assigns the value to the Browser property of the object that is presumably being defined outside of your code snippet.
You could also define the function somewhere:
function myFunction() {
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
IE: !!window.attachEvent && !isOpera,
Opera: isOpera,
WebKit: ua.indexOf('AppleWebKit/') > -1,
Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile.*Safari/.test(ua)
}
and then call it:
var foo = myFunction();
and then assign the value:
...
Browser: foo,
...
One downside with doing it that way is that you "pollute your namespace" with a function and a variable that you won't use anywhere else. The second issue is that you can't use the value of any locally-scoped variables in your function definition (the anonymous function behaves as a closure).
(function () {}) creates an anonymous function.
Adding the () to the end calls the function that was just created.
In the case of this particular function, the anonymous function returns several properties to the Browser object. So, you end up with boolean values for, e.g., Browser.IE, Browser.Opera, etc.
it calls the anonymous function that was just declared, effectively causing the "block" to be evaluated.
It's a simple function call, no different than foo() except it's invoking an anonymous function literal, the result of the function is assigned to the Browser property.