Reputation: 309
I'm pretty sure this is n00b question, but I'm completely new to javascript. I'm wondering why this code only prints "hello" but when I comment out the first function, that's when I get the second function to print the other two words. How does this make sense?
var function1 = createFunction();
function createFunction()
{
console.log("hello");
}
function1();
function createFunctionPrinter(word)
{
console.log(word);
}
var printSample = createFunctionPrinter('sample');
var printNoo = createFunctionPrinter('noo');
printSample(); //should console.log('sample');
printNoo(); //should console.log('noo');
Upvotes: 2
Views: 57
Reputation: 31682
var function1 = createFunction();
function createFunction()
{
// return a function that prints a message
return function() {
console.log("hello");
}
}
function1();
Upvotes: 0
Reputation: 6747
Fixing function1
and createFunction()
should be easy, provided the fact no arguments are needed for this. Simply set var function1 = createFunction
without ()
and you it will effectively make function1
call createFunction
as if that was the function's name.
createFunctionPrinter()
is a bit different. My preferred approach is the use of a prototype, which will take an argument (word
) when called, and then when you call its print()
method, it will essentially print your text. The assignment of printSample
and printNoo
is similar, but you have to use the new
keyword. Finally, to make the functions print, use something like printSample.print()
.
function createFunction() {
console.log("hello");
}
function createFunctionPrinter(word) {
this.word = word;
this.print = function() {
console.log(word);
}
}
var function1 = createFunction;
function1();
var printSample = new createFunctionPrinter('sample');
var printNoo = new createFunctionPrinter('noo');
printSample.print();
printNoo.print();
P.S.: This might not the intended use of prototypes, but I believe it will make your life easier to use them in this case.
Upvotes: 1
Reputation: 3719
If you want to refer to an method, you should leave the ()
, as the function call return undefined
.
See this example
function createFunction()
{
console.log("hello");
}
var function1 = createFunction;
function1();
function createFunctionPrinter(word)
{
console.log(word);
}
var printSample = createFunctionPrinter;
var printNoo = createFunctionPrinter;
printSample('sample'); //should console.log('sample');
printNoo('noo'); //should console.log('noo');
Upvotes: 1
Reputation: 943214
function1
is the return value of calling createFunction
which is undefined
because createFunction
has no return
statement.
undefined
is not a function, so calling function1()
raises an exception and execution halts.
Upvotes: 3