Let's take a look at an example:
Copy codeThe Code is as follows:
Var Class = {
Create: function (){
Return function (){
This. initialize. apply (this, arguments );
}
}
}
Var A = Class. create ();
A. prototype = {
Initialize: function (){
// Todo
}
Test: "abc"
}
Var a = new ();
This is a process in which many jser construct classes and instantiate objects. Careful people will find that the instantiated a will have an initialize method. Initialize does not have any meaning after being instantiated as a proxy during instantiation, and sometimes it will cause unnecessary troubles, such as... When the in statement traverses a, the initialize method is traversed.
The first thing I think of is to use Class. js written in the previous blog post, which is very clean. However, the Inheritance Mechanism in Class. js has some bugs. It is even more difficult to implement interfaces without intrusion (I .e., without modifying the prototype or generating additional attributes. So I thought about encapsulating the new operator. The advantage of doing so is that we can first modify the prototype and implement inheritance and interfaces in the new encapsulation method, and remove additional attributes.
Let's first give a simple implementation of the new operator:
Copy codeThe Code is as follows:
Function New () {// new is the keyword, so make a difference
Var as = [], args = arguments;
For (var I = 1; I <args. length; I ++ ){
As. push ('args ['+ I +'] ');
}
Nobj = eval ("new args [0] (" + as. join (",") + ");");
Return nobj;
}
Next, let's test:
Function A (n) {this. name = n ;}
Var a1 = new A ('ts ');
Alert (a1.name); // ts
Var a2 = New (A, 'tangoboy ');
Alert (a2.name); // tangoboy
The test is successful. Now, the New method can basically instantiate the object instead of the new operator.
Then it is very easy to solve the initialize problem at the beginning of the article:
Function New (){
Var as = [], args = arguments;
For (var I = 1; I <args. length; I ++ ){
As. push ('args ['+ I +'] ');
}
Nobj = eval ("new args [0] (" + as. join (",") + ");");
Delete nobj. initialize; // Method for deleting an instantiated object
Return nobj;
}
In the next section, enrich the New method.