Home  >  Article  >  Web Front-end  >  Using methods to encapsulate the new operator of javascript (1)_javascript skills

Using methods to encapsulate the new operator of javascript (1)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:13:311084browse

Let’s look at an example first:

Copy the code The 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 A( );

This is the process of constructing classes and instantiating objects in many jser. Careful people will find that: the instantiated a will have an additional initialize method. When initialize is used as a proxy during instantiation, it has no meaning after instantiation, and sometimes it causes unnecessary trouble. For example, when the for...in statement traverses a, the initialize method will be traversed.
The first thing I thought of was to use Class.js written in the previous blog post, which is very clean. However, there are some bugs in the inheritance mechanism in Class.js. It is even more difficult to implement the interface without intrusion (that is, without modifying the prototype or generating additional attributes). So I thought of encapsulating the new operator. The advantage of this is that the prototype can be modified first, and in the method of encapsulating new, inheritance and interfaces can be implemented, and additional attributes can be removed.
Let’s first implement a simple implementation of the new operator:
Copy the code The code is as follows:

function New(){//new is a keyword, so distinguish it
var as = [],args = arguments;
for(var i=1;ias.push('args[' i ']');
}
nobj = eval("new args[0](" as.join(",") ");") ;
return nobj;
}
Test it next:
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 is basically You can instantiate objects instead of the new operator.
Then it is very simple to solve the initialize problem at the beginning of the article:
function New(){
var as = [],args = arguments;
for(var i=1;ias.push('args[' i ']');
}
nobj = eval("new args[0](" as.join(",") " );");
delete nobj.initialize;//Delete the method of instantiated object
return nobj;
}

The next section begins to enrich the New method.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn