The problems encountered are first of all the encapsulation of js objects. js does not provide a class mechanism. The only built-in class is the function class, which means that all functions are instantiated objects of the function class. However, relying on this unique class we can simulate defining a new class.
The first thing that comes to mind is to directly use function to generate a fully defined class:
function myClass(arg,...)
{
this.attributeName;
this.functionName = function(){};
}
But there is a problem with this. Whenever I create a new myClass instance, the internal function will reopen the space and return a reference to functionName. But this is inconsistent with the class we imagined and wastes space. In theory, the functions of the class should be shared.
A more reasonable approach is to define the function outside the class and then assign the function pointer to functionName inside the class. The other is to use myClass.prototype.functionName = function(){} outside the class. Both are good choices, the second of which looks closer to the class definition.
Next, var newObj = new myClass(); and you’re done.
About js (2) Unnamed functions
One of the functions of unnamed functions may be to generate a reference to a new function object, mainly for definition.
Another use is for some callback functions in js that cannot contain parameters.
The obvious example is setInterval. I think this is a function that gives many people a headache, especially when you want to add parameters to the callback function.
And the most troublesome thing is that DHTML is not a standard specified by w3c, so different browsers give different setInterval parameter tables. . .
As for the two browsers I tested (IE core, webkit core)
IE: setInvterval(function, msecond [,lang]);
chrome:setInterval(function, msecond [, pram1, pram2, ....]);
In other words, chrome allows adding parameters to functions, and the parameter list is at the end. However, the last parameter of IE is to indicate the type of scripting language used, because in addition to js, IE also supports other scripting languages such as vbs.
In order to solve the problem of compatibility, we have to use unnamed functions. . .
function test(yourArg)
{
var arg = yourArg;
setInterval(function(){callback(arg)}, time);
}