Home >Web Front-end >JS Tutorial >What are the methods of javascript object encapsulation?

What are the methods of javascript object encapsulation?

coldplay.xixi
coldplay.xixiOriginal
2021-04-30 16:11:422602browse

Javascript object encapsulation method: 1. Use conventional encapsulation, the code is [function Person (name, age, sex)]; 2. Common method, the code is [constructor: Person,_init_:function(info )].

What are the methods of javascript object encapsulation?

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Javascript object encapsulation method:

Conventional encapsulation

function Person (name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
 
Pserson.prototype = {
    constructor:Person,
    sayHello:function(){
        console.log('hello');
    }
}

This method is more common and more intuitive, but Person() The responsibility is to construct the object. If the initialization is also done in it, the code will be cumbersome. Would it be better if it is initialized in a method?

Upgraded version (common)

function Person (info){
    this._init_(info);
}
 
Pserson.prototype = {
    constructor : Person,
    _init_ : function(info) {
        this.name = info.name;
        this.age = info.age;
        this.sex = info.sex;
    }
    sayHello:function(){
        console.log('hello');
    }
}

However, at this point, I discovered that name, age, and sex were not stated in Person. Where did they come from???

Related free learning recommendations: javascript video Tutorial

The above is the detailed content of What are the methods of javascript object encapsulation?. 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