Let’s look at a simple piece of code first:
var testFun=function ( name,age){
var job='Flash Develop';
return new testFun.init(name,age,job);
}
testFun.init=function(name,age,job) ){
return 'name:' name ',age:' age ',job:' job '';
}
alert(testFun('vincent',30)); //[object Object ]
The code is very simple. The variable testFun is an anonymous function, and the anonymous function returns a testFun.init object (also an anonymous function). But for some novices, they sometimes misunderstand that testFun is a testFun.init object returned. He may think that testFun was used again during the construction process of the anonymous function function (name, age). At this time, testFun is still being built and should not exist yet, and testFun.init does not exist, so how can testFun be used. What about init?
In fact, there is a misunderstanding in thinking this way: testFun is equated with testFun(). If testFun is a testFun.init object returned, the code should be testFun=function(name,age) {… …}(). The correct understanding should be this. testFun is just a function. When you assign a function to it, it already exists. Even if the function returns undefined or null, it itself is still a Function. Only after testFun() is executed The return value is undefined or null. The return value is the result of testFun() execution. After the result is returned, it no longer has anything to do with testFun. For example:
var testFun=function(){
return undefined;
}
var result=testFun();
alert(testFun); // function () {return undefined;}
alert(result); // undefined result is different from testFun There is no relationship anymore
So, when an anonymous function is assigned to testFun, it will always exist until another value is assigned to it. You can understand testFun.init simply like this:
testFun.init=function(name,age){}.init=function(name,age.job){… …}
To sum up, Looking back, testFun is a function, and testFun() is (function(name,age,job){return 'name:' name ',age:' age ',job:' job ''; })()
In order to facilitate understanding, the code can be simplified to:
var testFun=function(){}
testFun.init=function(){}
It’s just that testFun() does not return a testFun.init object.