Storing a Function in an Object's Property - javascript

Let's say I have a JavaScript object, foo, that has a property, "bar", whose value is a function.
var foo = {"bar" : someFunction};
I could replace "someFunction" with an anonymous function. However, what if I wanted to define the function separately:
function someFunction() {
...
}
I can't write foo.bar = someFunction() since it will store the result of evaluating the function.
How can I set foo.bar's value to a function? How would I call it once it's set?

How can I set foo.bar's value to a function?
Without the parentheses:
foo.bar = someFunction;
How would I call it once it's set?
Treat the property as you would any function:
foo.bar();

You should simply assign the bar to some someFunction pointer, like this:
var foo = {};
function someFunction() {
};
foo.bar = someFunction;
foo.bar();

Take out the () and you should be able to set it equal to a function
foo.bar = someFunction; //assign
foo.bar(); // call
http://jsfiddle.net/sN9cs/1/

The first example is exactly how you do it. Just don't call the function:
foo.bar = someFunction;

Related

Javascript method assignment when no brackets

I have a java script as below
foo(){
return "hello";
}
var myVar=foo;
What will get assigned to myVar?
if you initialize it with function keyword:
function foo() {
return "hello";
}
then it is possible as in JavaScript in function is a Data Type so you initialized a variable named foo and then assign another variable.
var myVar = foo;
Calling now myVar() will call function as it has reference to that function now.
Here is Demo
SyntaxError Error.
I think what you want is this? In this case foo is an alias for this funciton defined
var foo = function(){
return "hello";
}

Js prototype , setting name

I don't mean a name property, e.g
String.prototype.myFunc = function(){}
var myString = new String();
console.log(myString);
When you view the created function in the console, there is a name:''. I was wondering how we set this.
Use a named function:
String.prototype.myFunc = function myFunc(){};
You can construct a function with a function declaration statement and then assign it to the prototype property of your choice:
(function() { // to keep the global scope clean
function myFunc() {
// whatever
}
String.prototype.myFunc = myFunc;
})();
You can in fact give a name to any function in a function instantiation expression, but it's not a super-safe thing to do.
You did you an anonymous function, whose name property is the empty string.
Either use a named function expression:
String.prototype.myFunc = function myNamedFunc(){};
or assign a function which you declared with a name:
function myNamedFunc() {};
String.prototype.myFunc = myNamedFunc;

var foo = (function(){...})(); ... foo() doesn't work

as expected it invokes the function foo the first time, but when i want to use the function another time the following error is thrown:
Uncaught TypeError: Property 'foo' of object [object DOMWindow] is not a function
the intention was to define a function (which has to be called immediately, but also later on) - do i have to write the following instead:
function foo() {...}
foo();
... // later on
foo();
or is there a more elegant solution?
EDIT: if you cannot use a variable (even if it's an anonymous function) as a function, what is its advantage anyway?
(why does
var foo = (function(){...})();
... // later on
foo();
not work?)
If you expand
var foo = (function(){...})();
foo();
you will get this:
function temp() {
...
}
foo = temp();
As you can see, you are calling the temp function (bolded here): var foo = (function(){...})();. This means that foo is not being assigned to a function object, but the return value of that function call. Therefore, unless the temporary function returns a function (and in that case you might want to consider refactoring), the value stored in foo will not be callable.
In JavaScript, there are two ways to store a function object:
A) Pass a function without calling it (i.e. foo = bar; instead of foo = bar()).
B) (If you need to pass parameters) pass a function call wrapped in another function (without calling the wrapper function) (i.e. foo = function {bar(param1, param2);}; instead of foo = function {bar(param1, param2);}(); (notice the () at the end? -- you don't want that)).
It does not work because you assign the result of calling the anonymous function to foo, instead of the function itself.
When you then try to call foo(), you are trying to treat the result of the first function call (apparently of type DOMWindow) as a function, which is incorrect.
You could use
var foo;
(foo = function(){...})();
but this is not well-readable.
Shouldn't it be
var foo = function() { ..... }
instead of
var foo = (function() { .. } ) ();
in your case you are assigning a anonymous function to foo.

Function names ending with ()

How does JavaScript deal with functions with names ending with ()? Consider for example the following piece of code:
var foo() = function () { }; // The empty function
var bar = function(foo) { var myVariable = foo(); };
It seems like there are two possible interpretations for what foo(); means:
Execute the argument foo. This assigns myVariable the returned value of foo.
Consider foo() as the name of the function defined at first. This assigns myVariable the empty function.
Is this even legal code? If so, what are the rules?
Is this even legal code?
No:
var foo() = function () { };
should be:
var foo = function () { };
If so, what are the rules?
In this case the foo argument will have precedence because it is defined in an inner scope than the foo function. So it's really a matter of scope: where is the variable defined. The interpreter first starts by looking in the innermost scope of the code, then in the outer, ... until it reaches the global scope (the window object).
So for example the result of the following code will be 123 as seen in this live demo:
var foo = function () { alert('we are in the foo function'); };
var bar = function(foo) { var myVariable = foo(); alert(myVariable); };
bar(function() { return 123; });
The () isn't considered part of the name. You'll probably get a syntax error. You can find some naming rules here.
In javascript, brackets mean execute. So your code will fail as it will be looking for a function foo on the first line.
Identifiers may not contain any parentheses, so the first statement is illegal. The second, however, is fine, myVariable = foo() executes the foo parameter and assigns the return value.
Do you really mean "Can I pass functions as references?" If so, then the answer is yes:
var foo = function() { return 2; }
var bar = function(fn){ return fn(); }
var two = bar(foo);

Declaring variables with this or var?

What is the difference between declaring a variable with this or var ?
var foo = 'bar'
or
this.foo = 'bar'
When do you use this and when var?
edit: is there a simple question i can ask my self when deciding if i want to use var or this
If it is global code (the code is not part of any function), then you are creating a property on the global object with the two snippets, since this in global code points to the global object.
The difference in this case is that when the var statement is used, that property cannot be deleted, for example:
var foo = 'bar';
delete foo; // false
typeof foo; // "string"
this.bar = 'baz';
delete bar; // true
typeof bar; "undefined"
(Note: The above snippet will behave differently in the Firebug console, since it runs code with eval, and the code executed in the Eval Code execution context permits the deletion of identifiers created with var, try it here)
If the code is part of a function you should know that the this keyword has nothing to do with the function scope, is a reserved word that is set implicitly, depending how a function is called, for example:
1 - When a function is called as a method (the function is invoked as member of an object):
obj.method(); // 'this' inside method will refer to obj
2 - A normal function call:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
3 - When the new operator is used:
var obj = new Constructor(); // 'this' will refer to a newly created object.
And you can even set the this value explicitly, using the call and apply methods, for example:
function test () {
alert(this);
}
test.call("hello!"); //alerts hello!
You should know also that JavaScript has function scope only, and variables declared with the var statement will be reachable only within the same function or any inner functions defined below.
Edit: Looking the code you posted to the #David's answer, let me comment:
var test1 = 'test'; // two globals, with the difference I talk
this.test2 = 'test'; // about in the beginning of this answer
//...
function test4(){
var test5 = 'test in function with var'; // <-- test5 is locally scoped!!!
this.test6 = 'test in function with this'; // global property, see below
}
test4(); // <--- test4 will be called with `this` pointing to the global object
// see #2 above, a call to an identifier that is not an property of an
// object causes it
alert(typeof test5); // "undefined" since it's a local variable of `test4`
alert(test6); // "test in function with this"
You can't access the test5 variable outside the function because is locally scoped, and it exists only withing the scope of that function.
Edit: In response to your comment
For declaring variables I encourage you to always use var, it's what is made for.
The concept of the this value, will get useful when you start working with constructor functions, objects and methods.
If you use var, the variable is scoped to the current function.
If you use this, then you are assigning a value to a property on whatever this is (which is either the object the method is being called on or (if the new keyword has been used) the object being created.
You use var when you want to define a simple local variable as you would in a typical function:-
function doAdd(a, b)
{
var c = a + b;
return c;
}
var result = doAdd(a, b);
alert(result);
However this has special meaning when call is used on a function.
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
doAdd.call(o, a, b);
alert(o.c);
You note the first parameter when using call on doAdd is the object created before. Inside that execution of doAdd this will refer to that object. Hence it creates a c property on the object.
Typically though a function is assigned to a property of an object like this:-
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
o.doAdd = doAdd;
Now the function can be execute using the . notation:-
o.doAdd(a, b);
alert(o.c);
Effectively o.doAdd(a, b) is o.doAdd.call(o, a, b)
var foo = 'bar'
This will scope the foo variable to the function wrapping it, or the global scope.
this.foo = 'bar'
This will scope the foo variable to the this object, it exactly like doing this:
window.foo = 'bar';
or
someObj.foo = 'bar';
The second part of your question seems to be what is the this object, and that is something that is determined by what context the function is running in. You can change what this is by using the apply method that all functions have. You can also make the default of the this variable an object other than the global object, by:
someObj.foo = function(){
// 'this' is 'someObj'
};
or
function someObj(x){
this.x=x;
}
someObj.prototype.getX = function(){
return this.x;
}
var myX = (new someObj(1)).getX(); // myX == 1
In a constructor, you can use var to simulate private members and this to simulate public members:
function Obj() {
this.pub = 'public';
var priv = 'private';
}
var o = new Obj();
o.pub; // 'public'
o.priv; // error
Example for this and var explained below:
function Car() {
this.speed = 0;
var speedUp = function() {
var speed = 10; // default
this.speed = this.speed + speed; // see how this and var are used
};
speedUp();
}
var foo = 'bar'; // 'var can be only used inside a function
and
this.foo = 'bar' // 'this' can be used globally inside an object

Categories

Resources