Home  >  Article  >  Web Front-end  >  Encapsulation of information in JavaScript Introduction to js objects_js object-oriented

Encapsulation of information in JavaScript Introduction to js objects_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:29:16939browse

Encapsulation of information in JavaScript
Before coding, we need to understand the following terms;
Encapsulation: hiding the representation and implementation details of internal data;
Private properties and methods: the outside world can only use it The public interface allows access and interaction with it
Scope: In JavaScript, only functions have scope, and the properties and methods defined inside the function are inaccessible from the outside
Privileged methods: declared inside the function, they can access the inside of the function The variable (attribute) method consumes more memory;

Copy code The code is as follows:

function Person()
{
/*
* Declare private data
* Nickname, age, email
*/
var nickName, age, email;
/*
* Methods that need to access private data (privileged methods)
* Each instance generated will generate a new copy for the privileged method
*/
this.setData = function(pNickName, pAge, pEmail)
{
nickName = pNickName;
age = pAge;
email = pEmail
};
this.getData = function()
{
return [nickName, age, email];
}
}
/*
* Methods that do not require direct access to private data (public methods)
* No matter how many instances are generated, public methods only exist in memory One copy
*/
Person.prototype = {
showData: function()
{
alert("Personal information:" this.getData().join());
}
}


External code accesses internal properties through private or public methods
Copy code The code is as follows:

var p = new Person();
p.setData("sky", "26", "vece@vip.qq.com") ;
p.showData();

Demo code:

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> function Person() { var nickName, age, email; this.setData = function(pNickName, pAge, pEmail) { nickName = pNickName; age = pAge; email = pEmail }; this.getData = function() { return [nickName, age, email]; } } Person.prototype = { showData: function() { alert("个人信息:" + this.getData().join()); } } var p = new Person(); p.setData("脚本之家", "4", "admin@jb51.net"); p.showData(); </script>
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