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?
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.
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.)
var myFunc = MyFunc(), what object does this line create?MyFunc() and assigns the return result from the function to the myFunc variable just like var el = document.getElementById("header"); would.var myFunc = new MyFunc();? When you call a function via new, the JavaScript engine creates a blank object, assigns its prototype from MyFunc.prototype, and then calls MyFunc with this set to refer to the new object. In the normal course of things, MyFunc would use this to initialize some properties, and the result of the new expression would be the object that was created. (It's possible for MyFunc to cause the new object to be thrown away and make the result of the new expression refer to a different object, but that's both advanced and unusual.)MyFunc doesn't return a value, if you just call it (x = MyFunc();), x will receive undefined (not null). If you call it via new (x = new MyFunc();), x will receive a reference to the object created by new (see my overlapping comment above).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();
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() {
}
The case doesn't match. Javascript is case sensitive.