Home  >  Article  >  Backend Development  >  Use JavaScript to encapsulate a class

Use JavaScript to encapsulate a class

韦小宝
韦小宝Original
2018-03-14 17:26:502219browse

This article describes how touse JavaScriptto encapsulate a class. If you don’t know about using JavaScript to encapsulate a class or are interested in using JavaScript to encapsulate a class, then let’s take a look at this article. Let’s write the article, let’s cut the nonsense and get to the point

JavaScripters who have learned otherobject-oriented languages ​​may have used classes, such as: class{}, and a series of methods defined by them. ,
But when beginners learn js, they often see this sentence, that is, JavaScript is an object-oriented language, but no matter how much I learn, I don’t know much about object-oriented programming. The same is true for me. I am struggling with js object-oriented programming. I have understood it somewhat in the past few days. Let me talk about my understanding of js classes. . .

The so-called class will have the following functions:

1. Constructor

2. Static properties and static methods

3. Shared properties and shared methods

4. Private attributes, private methods

This article will talk about how to use js to encapsulate classes and realize the above functions,

1. A simple Class

var Person = function(name, age){
    this.name = name;    this.age = age;    this.sayName = function(){
        console.log(this.name);
    };
}

If you think it doesn’t look like a class, then you can do this

var Person = function(name, age){
    //共有属性
    this.name = name;    this.age = age;    //共有方法
    this.sayName = function(){
        console.log(this.name);
    };
}

If you are not clear about the constructor pattern, you can see Look here jsCreating objectsDesign pattern

2. A complex class

After having the above example, we will build on this basis We can then proceed with our improvements.

var Person = function(name, age){
    //共有属性
    this.name = name;    //共有方法
    this.sayName = function(){
        console.log(this.name);
    };    //静态私有属性(只能用于内部调用)
    var home = "China";    //静态私有方法(只能用于内部调用)
    function sayHome(){
        console.log(home);
    }    //构造器
    this.setAge = function(age){
        console.log(age + 12);
    };    this.setAge(age);
}//静态方法(只能被类来访问)Person.sayAge = function(){
    console.log("your age is 12");
}//静态属性(只能被类来访问)Person.drink = "water";//静态共有方法(类和实例都可以访问)Person.prototype.sayWord = function(){
    console.log("ys is a boy");
}

JS uses the above simulation method to realize the creation of classes. On this basis, we are not satisfied with the status quo and want to encapsulate it and make it a whole, which is more conducive to the encapsulation of JS. sex.

3. Encapsulating js classes

Here we use closures to implement it. First, explain the concept of closures.
Closure concept: A function has the right to access variables in another function scope, that is, creating another function inside a function

The implementation is as follows:

var Person = (function(){
    //静态私有属性方法
    var home = "China";    function sayHome(name){
        console.log(name + "'s home in " + home);
    }    //构造函数
    function _person(name, age){
        var _this = this;        //构造函数安全模式,避免创建时候丢掉new关键字
        if(_this instanceof _person){            //共有属性, 方法
            _this.name = name;
            _this.getHome = function(){
                //内部访问私有属性,方法
                sayHome(_this.name);
            };
            _this.test = sayHome; //用于测试
            //构造器
            _this.setAge = function(age){
                _this.age = age + 12;
            }(age);
        }else{            return new _person(name, age);
        }
    }    //静态共有属性方法
    _person.prototype = {
        constructor: _person,
        drink: "water",
        sayWord: function(){
            console.log("ys is a boy");
        }
    }    return _person;
})();

The call is as follows:

var p1 = new Person("ys", 12);
p1.getHome();                   //ys's home in China
console.log(p1.age);            //24     

var p2 = Person("ys", 12);
p2.getHome();                   //ys's home in China
console.log(p2.age);            //24   

console.log(p2.test == p1.test);  //true, 证明静态私有变量共享性

Like the above code, we use js to implement the class

Summary:

1. Some public properties and methods can be set to Static, so that every time it is instantiated, there is no need to open up additional memory resources to achieve true sharing.

2. Some public attribute methods only want to be shared during internal program processing. , then set it to a static private property method,

3. If you want to share some public property methods in the instance object, set it to a prototype property method,
The above is all the content of this article , if you don’t know much about it, you can easily master it if you can implement both sides by yourself!

Related recommendations:

Various writing methods of javaScript encapsulation

Javascript encapsulation Detailed explanation of mobile phone class function code examples

The above is the detailed content of Use JavaScript to encapsulate a class. For more information, please follow other related articles on the PHP Chinese website!

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