Home >Web Front-end >JS Tutorial >What are the methods of javascript object encapsulation?
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 )].
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!