Reputation: 21714
I have the below code,
function MyFunc(){}
var myFunc = new MyFunc();
myFunc(); // through TypeError this line,
How can I make it to work if I want to call the function through the variable?
Upvotes: 0
Views: 264
Reputation: 1075785
In JavaScript, functions are first-class objects. To refer to the object, just use the function name. So if you just want to call MyFunc
through the myFunc
variable, just assign MyFunc
to myFunc
:
function MyFunc(){}
var myFunc = MyFunc; // <=== Change on this line
myFunc();
Your original line:
var myFunc = new MyFunc();
...calls MyFunc
as a constructor function, and myFunc
(the variable) will receive a reference to whatever object is created as a result. (Just like, say, var now = new Date();
creates a Date
object and assigns it to now
.)
Upvotes: 2
Reputation: 39580
I think what you wanted is this:
var myFunc = function(){
....
};
myFunc();
This creates a variable named myFunc
which is a reference to the anonymous function.
Upvotes: 1
Reputation: 3432
So calling new MyFunc()
will excute whatever code you put in there - it acts somewhat like a constructor in other languages - although not exactly.
If it wasn't a typo and you wanted to define a function on your class called myFunc if you wanted by doing something like
MyFunc.prototype.myFunc = function() {
}
Upvotes: 1
Reputation: 30855
you create the object of the function the new keyword was used to create the object
var myfun_var = function MyFunc(){
alert("hello");
}
and call myfun_var();
Upvotes: 1
Reputation: 129746
By doing new MyFunc()
, you're treating MyFunc
as a constructor and are creating an object with it. This is treating MyFunc
as a class that you want an instance of. You just want to assign another variable to point to the function, so you don't want the new
or the ()
.
You want to just set var myFunc = MyFunc
, and then calling myFunc()
will work.
Upvotes: 6
Reputation: 19375
In javascript, a function is just another variable.
function MyFunc(){}
is the same as
var MyFunc = function(){};
Thus this is also valid
function MyFunc(){}
var myfunc = MyFunc;
myfunc();
Upvotes: 1