I have two javascript modules. I need to pass a function argument to another file. But am getting reference error foo is not defined in line3. Please help.
1.test1.js
exports.foo= function foo(x){ //line1
// do something
}
test2 = require("test2") // line2
test2.bar(foo) //line3
2.test2.js
exports.bar= function bar(foo){
foo(123)
}
Problem is in line1 of test1.js:
exports.foo= function foo(x){
where function foo(x){... is a function expression.
Named function expressions do not create a function declaration of the same name, and the name supplied is only available inside the expression. (Possibly with the exception of some ancient versions of IE about which I care nothing)
You could either create foo as a function declaration and assign it:
function foo() { ... code }
exports.foo = foo;
or call it in line 3 as test2.bar(exports.foo)
use the following approach
module.exports = function foo(x){
//implementation
}
You should assign the function to a variable.
const foo = function foo(x){
// do something
}
test2 = require("./test2")
test2.bar(foo)
Related
When I execute below java script code I get error at "v.dummy();" line , please let me know where am I doing wrong.
function Test()
{
}
Test.prototype.foo = function () {
console.log('foo');
}
var v = new Test();
v.foo();
v.__proto__ = function dummy() {
console.log('__proto__');
};
v.dummy(); // Uncaught TypeError: v.dummy is not a function
__proto__ is just a reference of an object
You can't make it equal a new function, but you can do it like this:
v.__proto__.foo = function dummy(){}
I don't know what you are trying to do, but:
1) when you assign function to a variable, you may omit the name (dummy) and use an anonymous function (without a name). Function name is useless in this case.
And if you do
var x = function y(){ ... }
you can call it like this: x(), not y()
2) __proto__ should be an object, not a function
usage of foo is correct, therefore it works.
You may want to consider reading a good JS book.
With this code:
function thing(){
function majig(){
alert("done");
}
}
var mything = new thing();
mything.majig();
I'm getting this error:
TypeError: mything.majig is not a function
I've done javascript for some time, and I've done functions as part of functions and called them before. I know it has to be something simple I'm missing or forgetting, but various websearches (and poking around here) are getting me deeper theory answers, or examples that seem to indicate that this should work.
I know TypeError: foo is not a function usually means a syntax error. I've looked up examples, and it looks like I have the syntax right (I've tried a few variations with no success).
It's got to be some dumb simple mistake, but I'm just not catching it right now. What do I do in my function to make the mything.majig(); run properly?
You have declared a function in thing, but it's not attached to this at all. Try this:
function thing(){
this.majig = function() {
alert("done");
}
}
var mything = new thing();
mything.majig();
Alternately:
function thing() {
return {
majig: function() {
alert("done");
}
};
}
Or, better yet:
function thing() { }
thing.prototype.majig = function () {
alert('done');
}
The syntax is not what you think it means. It's not a member declaration. It's an inner function. Inner functions work just like local variables - they're only accessible in the scope of the outer function:
function foo () {
function bar () {}
bar(); // accessible here
}
bar(); // undefined here
If your function is a constructor, then to add a member function to the object that it constructs you'd add it to the constructor's prototype:
function Foo () {}
Foo.prototype.bar = function () {}; // bar is a member of object Foo
var f = new Foo();
f.bar(); // call member function
Objects in javascript are dynamic. They behave more like maps/hashes do in other languages. This means you can add a member function directly to an object instead of a constructor's prototype:
var f = {};
f.bar = function () {};
f.bar(); // call member function
Following the logic above, since this in a constructor refers to the object being constructed, you can also dynamically add a function to this. This is typically called "decoration" since it is effectively an ad-hoc version of the decorator design pattern:
function Foo () {
this.bar = function () {}
}
var f = new Foo();
f.bar();
I have tried folllowing two ways of referring a function:
First
let a = function() {
somefunction();
}
Second
let a = somefunction;
Where somefunction is the following in both cases:
function somefunction() {
alert("hello");
}
Is there any difference between these two ways?
Yes, there is a difference between your two examples.
In the first case, you are defining a new anonymous (unnamed) function which calls somefunction. You are then assigning your new function definition to the variable a. a holds a reference to your new function.
In the second case, you are simply assigning your original function of somefunction to the variable a. The variable a then holds a reference to somefunction. You are not creating a new function as you are in the first case.
I think this example may make the difference clear. arguments is an array like object that contains each of the arguments passed to a function.
Try running each of these lines on your favorite browser console.
var somefunction = function() { console.log(arguments); };
Your first example demonstrates defining a named function a that closes around the named function somefunction.
var a = function() { somefunction(); };
Your second example makes a reference, b, directly to somefunction. This makes invoking b the same as invoking somefunction.
var b = somefunction;
Now if you call each of these a and b with some arguments you will see the difference.
=> a('a', 1);
[]
=> b('a', 1);
['a', 1]
In the first case the arguments object is empty. That's because the arguments that were passed to a were not forwarded onto somefunction.
In the second case the arguments are available to somefunction, because some function is being called directly.
Here is how you could redefine a so that it were functionally equivalent using apply
var a = function() { somefunction.apply(this, arguments); }
Running this at your console prints the argument array.
=> a('a', 1);
['a', 1]
var a = function(){
somefunction();
}
Is an Anonymous Function attributed to a variable.
somefunction :function() {
alert("hello");
}
Is an declaration of a function throungh the Object Literal notation.
The diference are shown when you are creating an object. The anonymous function are not acessible as a "public" method, instead in the Object Literal notation, that are acessible from outside.
As Douglas Crockford said, in JS the Good Parts, the first declaration are just a function and the second one could be a method.
In the first case, you are creating a function which calls someFunction(), then you assign that function to a, so now calling a() calls an anonymous function which in turn calls someFunction().
In the second case, a and someFunction become the exact same thing, calling a() is the same as calling someFunction().
The way you're setting var a by accessing the function is clearly out of scope.
So I suspect you have a typo : instead of = :
var somefunction = function() {
alert("hello");
};
somefunction(); // hello
...Now that your first and second makes sense with the code above:
Anonymous Function stored in variable:
var a = function(){
alert('Hey');
somefunction();
};
a(); // Hey // hello
Variable as Function Reference
var a = somefunction;
a(); // hello
In the other case than:
var objLiteral = {
somefunction : function() {
alert("hello");
}
};
var a = objLiteral.somefunction;
a(); // hello
function shortUrl () {
$['post']('http://tinyurl.com/api-create.php?url=http://json-tinyurl.appspot.com/', function (a) {
});
};
I Want to make this function as a var so I can use shortUrl Anywhere in my script. Like
var shortaddress = shortUrl ();
I want to use the result in next function.
function shortUrl () {...}
is equivalent to
var shortUrl = function () {...};
So, it is already a variable.
A function is already a variable, so you can use it as such. For instance:
function foo() {
// ...
};
is more or less the same as
var foo = function() {
// ...
};
Basically, if you drop the parentheses and arguments (foo instead of foo()), you can use any function as a normal variable.
Therefore you can for instance assign it to other variables, like you normally would:
var bar = foo; // note: no parentheses
bar(); // is now the same as foo()
Or you can pass it as an argument to another function:
function callFunc(func) {
func(); // call the variable 'func' as a function
}
callFunc(foo); // pass the foo function to another function
If you want to use the shortUrl function anywhere, it must be declared in global scope. Then that variable becomes a property of Window object. For example the following variables
<script type="text/javascript">
var i = 123;
function showA(){ alert('it'); window.j = 456; }
var showB = function() { alert('works'); var k = 789; this.L = 10; }
</script>
are declared directly in Window object and so become its attributes. Thus now they can be easily accessed from any script. For example all the following commands work:
<script type="text/javascript">
alert(i); alert(window.i);
showA(); window.showA();
showB(); window.showB();
alert(j); alert(window.j);
alert(new showB().L); // here the function was called as constructor to create a new object
</script>
Functions in javascript are objects and so they can hold attributes in themselves.
In the example above you can consider the k variable to be a private property and the L variable a public property of the showB object(or function). And another example: if you include jQuery library in your page, jQuery usually exposes itself as window.jQuery or window.$ object. Just it's generally recommended to use global variables very sparely and carefuly to prevent possible conflicts.
In the following JavaScript code main() is called.
My question is why the second constructor is called rather than the first one ?
What am I missing here ?
Thanks !!
function AllInputs() {
alert("cons 1");
this.radioInputs = [];
alert(this);
}
function AllInputs(radioElement) {
alert("cons 2");
this.radioInputs = [radioElement];
alert(this);
}
AllInputs.prototype.toString = function() {
return "[object AllInputs: radioInputs: " + this.radioInputs.length + "]";
}
function main() {
var result = new AllInputs();
}
Javascript does not support overloaded functions.
When you define the same function twice, the second definition replaces the first one.
Instead, you should make a single function, and check arguments.length to see how many arguments were passed.
For example:
function AllInputs(radioElement) {
this.radioInputs = arguments.length ? [radioElement] : [];
alert(this);
}
In JavaScript, the last definition of an identifier is used:
function foo() { return "bar"; }
var foo = "foo";
alert(foo);
In that case, foo was a variable with the value "foo". Had foo been a function, it would have simply said that foo was a function. If you don't believe it, try using alert(foo()) instead of just alert(foo). You'll most likely get an error in your console log with no visible output like you had with alert(foo) (the variable...not the function call).
function foo() { ... }
is really just shorthand for
var foo = function () { ... }
Hence, the second time you're declaring the function, you're overwriting the variable AllInputs with a different function. There ain't no such thing as two functions with the same name in Javascript, since all functions are really variables.