SoFunction
Updated on 2025-04-10

Prototype function analysis

Copy the codeThe code is as follows:

/**
* A well-designed timing actuator
* First, create a PeriodicalExecuter type from ()
* Then set the prototype using the syntax form of the object direct quantity.
*
* It should be noted that the rgisterCallback method, which calls the function prototype method bind defined above and passes itself as a parameter.
* This is done because setTimeout always takes the window object as the current object by default, that is, if the registerCallback method is defined as follows:
* registerCallback: function() {
* setTimeout(, * 1000);
* }
* Then, the method execution fails because it cannot access the property.
* Only after using bind can this method correctly find this, which is the current instance of PeriodicalExecuter.
*/
var PeriodicalExecuter = ();
= {
initialize: function(callback, frequency) {
= callback;
= frequency;
= false;

();
},

registerCallback: function() {
setTimeout((this), * 1000);
},

onTimerEvent: function() {
if (!) {
try {
= true;
();
} finally {
= false;
}
}

();
}
}

For specifics, what is done behind(), let’s take a look at the implementation of Class.
Copy the codeThe code is as follows:


/**
* Create a type, note that its property create is a method, returning a constructor.
* Generally used as follows
* var X = (); Returns a type similar to a Class instance of java.
* To use the X type, you need to continue to use new X() to get an instance, just like the () method of java.
*
* The returned constructor will execute a method named initialize, which is the constructor method name of the Ruby object.
* At this time, the initialize method has not been defined yet. When creating a new type in the subsequent code, the corresponding method with the same name will be established.
*/
var Class = {
create: function() {
return function() {
(this, arguments);
}
}
}

In fact, it is returning a function, so what did you do when new? Refer to MDN

When the code new foo(...) is executed, the following things happen:

A new object is created, inheriting from .
The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), . if no argument list is specified, foo is called without arguments.
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
When new, the returned function will be executed, that is, execution (this, arguments); at this time this is the newly generated object, which means that all the initialization work of all objects is delegated to the initialize function.

-------

Why do you need to bind your initialize method to yourself here? ?