Extensive use of javascriptI encounter problems. The first is 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 An instantiation object 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 a new myClass instance is created, Internal functions will re-open space and return references 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 nameless functions
One of the functions of nameless 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 the setInterval parameter table given by different browsers is different. . .
As far as the two browsers tested (IE kernel, webkit kernel)
IE: setInvterval(function, msecond [,lang]);
chrome:setInterval (function, msecond [, pram1, pram2, ....]);
In other words, chrome allows adding parameters to function, 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); }
The above is the detailed content of How to define a class in javascript object-oriented?. For more information, please follow other related articles on the PHP Chinese website!