SoFunction
Updated on 2025-04-13

Four ways to call javascript named functions Recommended page 2/3


Discuss whether this is present in the function. When there is no this, an empty object {} is returned, and when there is this, a non-empty object is returned.
Define a function without this
Copy the codeThe code is as follows:

//The return value is the basic type
function fun() {
return "jack";
}

var c = new fun();
for (var atr in c) {
alert(atr);
}
alert(c);//[object Object]

The return value c is not "jack". From the fact that no attribute is output after the execution of for in, it can be seen that c is an empty object {}.

Let’s look at the function that has this. This function is actually writing a class. However, due to the flexibility of js, many strange writing methods have been created.
Copy the codeThe code is as follows:

//The return value is the basic type
function fun() {
= "tom";
return "jack";
}

var c = new fun();
for (var atr in c) {
alert(atr);//name
}
alert();//tom

The return value is not "jack". For in outputs the name attribute, and the last sentence outputs tom, indicating that the return value c is a non-empty object. The return "jack" here doesn't work at all. Therefore, when the function returns a value of a built-in type (basic type), calling the function in new way will lead to an incorrect result.

So what if the function returns a value as an object, array, function?
Copy the codeThe code is as follows:

//Not including this, the return value is an object
function fun() {
//Assemble an object
var obj = {};
= 'andy';
= 20;
= function(){}

return obj;
}

var c = new fun();
for (var atr in c) {
alert(atr);//name,age,msg
}
alert();//andy

Copy the codeThe code is as follows:

//Including this, the return value is an object
function fun() {
= "man";
//Assemble an object
var obj = {};
= 'andy';
= 20;
= function(){}

return obj;
}

var c = new fun();
for (var atr in c) {
alert(atr);//name,age,msg
}
alert();//andy

The output results of the two segments are the same, both c contains the name, age, msg attributes but not the sex attributes. Explanation: When the return value is an object type (object, array, function), new will not use this to construct the object, but will directly return the assembled object.

This method is actually the factory method. In applications, more programmers capitalize the initials of the function name to make it look more like a class.
Previous page123Next pageRead the full text