Home > Web Front-end > JS Tutorial > body text

What are the methods of javascript object encapsulation?

coldplay.xixi
Release: 2023-01-05 16:13:17
Original
2343 people have browsed it

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');
    }
}
Copy after login

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');
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!