JavaScript simulation class mechanism and private variable method and thinking _javascript skill

Source: Internet
Author: User
Tags closure
When you use some Javascript frameworks, you may see similar code
Copy Code code as follows:

var MyClass = new Class ({
Initialize:function (param, ...) {
This.param = param;
...
},
Func1:function (...) {
...
}
});
var myobj = new MyClass (param);
MYOBJ.FUNC1 (...);

This is a typical object-oriented application of the class mechanism, compared with the native Javascript class mechanism, it appears more clear and natural. And, on this basis, the implementation of class inheritance is also more convenient. So how did this happen?
As we all know, in Javascript, a function as a constructor, you can create an object, the above code can be simply written:
Copy Code code as follows:

function MyClass (param) {
This.param = param;
THIS.FUNC1 = function (..) {
...
};
}
var myobj = new MyClass (param);
Myobj.func1 ();

In fact it is quite simple, it is not difficult to understand. However, if you want to build a large set of Javascript class libraries, it may be confusing, from a heap of code to find out which is the class, which is the function, which is the class method, which is the class attribute, is a painful thing.
Of course, here is not to compare their pros and cons, just curious about the implementation of new Class.
In the above code, using a statement like new MyClass () means that the MyClass must be a function, and it means that the new Class needs to return a function object, which literally means that the function initialize is used as a constructor, so , in the function returned by the new Class, you must use initialize to initialize the object. Based on this analysis, the following code can be drawn:
Copy Code code as follows:

function Class (ARGU) {
return function () {
var init = argu[' Initialize '] | |  function () {}; If there is no constructor initialize, use an empty function as the default constructor
For (var p in Argu) {
THIS[P] = argu[p];
}
Init.apply (this, arguments); Use this of the current function instead of the function initialize the original this
}
}

The code above is not rigorous enough, but it is enough to illustrate the problem. Note the phrase init.apply (this, arguments), where there are several variants of the reference, one is this, the original initialize the default this, is now replaced by the return of this anonymous function of this, and this anonymous function, is through the new Class to create a new custom class constructor. The other is arguments, which refers to the parameters of the anonymous function, which is param in the new MyClass (param) above.
This conversion is somewhat giddy, so is there a simpler way to do it? Take a look at the following code:
Copy Code code as follows:

function Class (ARGU) {
var obj = argu[' Initialize '] | | function () {};
For (var p in Argu) {
OBJ.PROTOTYPE[P] = argu[p]; Attention, this is prototype.
}
return obj; It actually returns a function
}

Oh, feel a lot of straightforward.
This completes the construction of a simple class mechanism. With this mechanism, you can create constructors, methods, and properties of classes, but these are obviously public, so how do you implement private variables and methods?
We know that the private variables of Javascript classes can be done by the closure mechanism. However, it is obviously difficult to form a valid closure when you convert using the new Class ({...}). How do you get around this problem?
Javascript provides two methods: eval () and the ToString () method of the Function object, which is more common, and can be used to get the specific code of the function. By using these two methods, you can simply simulate the private variables of a class:
Copy Code code as follows:

function Class (ARGU) {
var _ = argu[' Private '] | | {};
Eval (' var obj = ' + (argu[' Initialize '] | | function () {}). ToString ());
For (var p in Argu) {
if (p = = ' Initialize ' | | p = = ' private ')
Continue
if (typeof argu[p] = = ' function ')
Eval (' obj.prototype[p] = ' + argu[p].tostring ());
Else
OBJ.PROTOTYPE[P] = argu[p];
}
return obj;
}

The code of functions is extracted by the toString () method of the function object and executed using the Eval method, so that a valid closure scope can be constructed to implement the private mechanism. We can apply the following:
Copy Code code as follows:

var person = new Class ({
Private: {
height:160,
Weight:50
},
Initialize:function (name, height, weight) {
THIS.name = name;
_.height = Height | | _.height;
_.weight = Weight | | _.weight;
},
Show:function () {
Alert (' Name: ' + this.name + '/nheight: ' + _.height + '/nweight: ' + _.weight ');
}
});
var i = new person ("en");
My.show ();

It doesn't look good, but in practical applications, it doesn't really have much use. Mainly in terms of efficiency, it takes about four times times more time than usual implementations. In the construction of large class libraries, this is intolerable, and in small applications, implementing the following code is simpler and more straightforward:
Copy Code code as follows:

function MyClass (param) {
var Privatevar = ...;
This.param = param;
This.func = function () {
alert (Privatevar);
};
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.