JavaScript implements the private, protected, public, static, and inheritance of classes

Source: Internet
Author: User

Classes in basic knowledge javascript

JavaScript is actually a weakly typed language, unlike languages such as C + + and Java. So, in JavaScript. The concept of class is not emphasized, but in practice, the class is very important, for example, to write a game. What if we kept calling the function to finish creating the role and moving the character? There might be a lot of repetitive code, so we need a class to unify the code. The so-called class, that is, the code in the program classification, for example, the game about the role of the code as a class, game background counts as a class, game special effects are a kind. In this way, we operate on the class. It doesn't make the code look messy. Jumbled. Although JS is a weakly typed language, it also provides the probability of a class.


Defines the class in JS, which is actually used function . It is well known that this syntax is actually used to define functions. Unlike defining functions, we are able to function this.xxx define properties and methods in the way that they are defined.

Say:

function People () {    this"Yorhom";    thisfunction () {        returnthis.name    };}

Use when using new :

varnew People();// "Yorhom"alert(yorhom.getName());

Can see. This allows you to use the methods in the classes and classes that we define.
You may be asked this.xxx to define only public properties and methods. What about the private properties and methods? This can use the knowledge of JS closures to solve:

 function people () {     This. Name ="Yorhom";varAge = -; This. GetName = function () {        return  This. name}; This. Getage = function () {        returnAge };}varYorhom =NewPeople ();//undefinedalert (yorhom.age);//Alert (Yorhom.getage ());

Can see that the age here is a private property.

The prototype in JavaScript

The drawback of the above code is that if a class has a very many methods, the same time to use the same class where there are very many (that is new , there are very many objects), then use the above code will be the memory of the problem of excessive consumption. The root cause of the problem is that each time an object is instantiated, the class executes the code in the constructor (the people class, for example, is function people () {...} Code to execute). So whenever this class is instantiated, these methods and properties are copied to the instantiated object. In this way, it will cause "eat" memory phenomenon.
So JS in the prototype birth. prototypeis generally used to add a series of constants or methods to a class. Each time a class is instantiated. An instantiated object takes its own initiative to obtain the prototype methods and properties defined in the class.

Just here to get a reference that is similar to C + +, does not replicate these methods and properties in memory, but points to these methods and properties. Demo Sample:

function People () {    this"Yorhom"function () {    returnthis.name;};varnew People();// "Yorhom"alert(yorhom.getName());

Such a method can save memory, but. In the ointment, you cannot define a private property.

Inheritance of Classes

JavaScript does not provide inherited functions. So just have to write it yourself.

Here we use the inheritance method in Lufylegend.js to show you how to implement inheritance:

function base (d, b, a) {    varnull, o = d.constructor.prototype, h = {};    forin o) {        1;    }    forin b.prototype) {        if (!h[p]) {            o[p] = b.prototype[p];        }    }    b.apply(d, a);}

The base here is the inheritance function. The principle of inheriting functions is to replicate the methods and properties of the class. So. Just to do this, you can implement the inheritance of the class. We can see in the code above that we iterate prototype to get the methods and properties defined in the prototype chain. applyreplication of properties and methods in the constructor is made by calling the constructor of the parent class. Use the Demo sample:

function People () {    this"Yorhom"function () {    returnthis.name;};function Student () {    base(this, People, []);}varnew Student();// "Yorhom"alert(yorhom.getName());
Definition of static properties and methods

Static properties and methods and the definition of static classes in JS are very easy. First look at the static class:

var StaticClass = {};

Isn't that the definition of the one you're writing Object ? Yes, that's good. Only the static class in JS can be defined as such. If you want to add methods and properties to a static class, you can write:

var StaticClass = {    5,    function () {        alert("Hello");     }};

Suppose you want to add a static property or method to a class that can be used as a notation:

function People () {    this"Yorhom"function () {    returnthis"people"function () {    alert("Hello");};
Implement a feature-rich class

As we mentioned above, saving memory and defining private properties is not both possible, yes, and "can't have both fish and bear paw" is a truth. In the usual process of use, we need to choose between these two items. But now this is the age. What's not to be combined with? Can't eat the same time with the cake? Of course not ... It is illegal to eat the bear's paw (to be researched)? But at least chicken and fish can be eaten at the same time.
Because JS does not implement the definition of a private property. So this is actually a no-clue job, because in standard practice we can prevent external access except closures. There's no other way. So here we are going to use a little astray method.

JavaScript Set/get Interview

What is the Set/get interview device? If you are familiar with Python, then you can understand @property and @xxx.setter , but the simple JS also have? There are, of course, just ES5 standards that can be used in this way:

Object.defineProperty(this"name", {    get : funtion () {        return name;    },    function (v) {        name = v;    }});

What's the use of detail? It is roughly the time that a this.name property is called when it is fetched get , and is called when the value is changed set .
You can understand the general wording from the above code, just assume you want to delve into this article: http://blog.csdn.net/teajs/article/details/22738851

Note that the above method of use will have compatibility issues. Browser support conditions such as the following:

PC-Side

Firefox Google Chrome Internet Explorer Opera Safari
4.0 5 9 11.6 5.1

Mobile side

Firefox Mobile Android IE Mobile Opera Mobile Safari Mobile
4.0 Yes 9 11.5 Yes

from: https://developer.mozilla.org/.../defineProperty#Browser_compatibility

How do I "astray" to prohibit access to private and protected properties?

This is a more troubling question, as we said at the beginning of this section, under conventional development. You can only block access to a variable by closing the packet.

But suppose you use it prototype . Then the closure of the road will not go through. In this case, we are on the pitch Object.defineProperty . We know that this function allows you to set the value that is returned when the property is obtained, and the value that is set when the property is changed.

With this function, we are able to keep track of whether a property is being fetched or not being changed. We also need a switch that, when we call the method inside the class, turns this switch on, indicating that it is executed internally. The switch is closed after the method call ends. Indicates the return to the external execution state.

With these two states, we are able to track private and protected properties and methods once they are used when the switch is closed. Terminates the acquisition or setting of this property or method.
So, the big problem is almost conquered.

Open Source Library Parts Jpp.js

With this astray thought in mind, I encapsulate this feature in Jpp.js, the GitHub address for the library, such as the following:
Https://github.com/yuehaowang/jpp.js
Of course, this library is not limited to creating a class. You can also implement overloading of functions, and so on. Now the library is still in the development stage, you are welcome to submit suggestions.

Create a class using Jpp.js
varPeople = JPP.class({extends:NULL,Private: {ID:NULL, Hobby:NULL},protected: {money:NULL, PhoneNumber:NULL}, Public: {firstName:NULL, LastName:NULL, Age:NULL, Birthday:NULL, Occupation:NULL, constructor: function (name, id) {            if(name) {varNameArray = Name.split (" "); This. FirstName = namearray[0]; This. LastName = namearray[1]; }if(ID) { This. id = ID; }}, Setbirthday: function (date) {            if(date) { This. Birthday = date; }}, Getbirthday: function () {            return  This. Birthday; }, Askforid: function () {            return  This. ID; }, Findhobby: function () {            return  This. Hobby; }    },Static: {occupation_programmer:"Programmer", Occupation_artist:"Artist", Occupation_musician:"Musician", Occupation_student:"Student"}});varPeter =NewPeople ("Peter Wong",543232123565);p eter.occupation = People.occupation_programmer;peter.setbirthday ("19980727");//Result:peteralert (peter.firstname);//result:19990727Alert (Peter.getbirthday ());//result:51092028Alert (Peter.askforid ());//Result:nullAlert (Peter.findhobby ());//Result:programmeralert (peter.occupation);//Erroralert (peter.id);

The above code is analyzed:
Using a jpp.class function to create a class, the function's parameter is an object, the object can be added to the following attributes such as:

    • extends the parent class when inheriting
    • private property, which is not available outside the defined members and cannot be inherited to subclasses
    • protected Load protection properties, which are not available outside the defined members but can be inherited to subclasses
    • public to load common properties
    • static loading methods and properties

In the process of creating a class, public constructor this.super You can access the parent class constructor by adding a method initialization constructor in.

Execute the code and be able to see the top 5 browsers performing correctly alert . And the last time the browser executes the error:

The detailed implementation process is a bit complicated. Just the principle is described in detail above. The code can be seen on GitHub, and you're welcome to study.

You are welcome to follow my blog

Reprint Please specify source: Yorhom's Game box

Http://blog.csdn.net/yorhomwang

JavaScript implements the private, protected, public, static, and inheritance of classes

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.