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: only external Can access and interact with it through its public interface
Scope: In JavaScript, only functions have scope, and the properties and methods defined inside the function are not accessible from the outside
Privileged methods: Declared inside the function, they can The method of accessing internal variables (properties) of a function consumes more memory;
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()); } }
External code accesses internal properties through private or public methods
var p = new Person(); p.setData("sky", "26", "vece@vip.qq.com"); p.showData();
Demo code:
<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("PHP中文网", "4", "admin@php.cn"); p.showData(); </script>
For more JavaScript information and related articles about encapsulating js objects, please pay attention to the PHP Chinese website!