当前位置:网站首页>Access to control objects in JS
Access to control objects in JS
2022-06-22 07:00:00 【webchang】
List of articles
One 、 Use getter and setter Control the properties of the access object
We can use common custom getter and setter Method To control access to properties .
// ordinary getter and setter, You need to call the relevant methods explicitly
function Person() {
let age = 10;// Used as a private property
this.getAge = function () {
console.log(" Get attribute value :");
return age;
}
this.setAge = function (value) {
console.log(' Setting property values :', value);
age = value;
}
}
let p1 = new Person();
console.log(p1.getAge());
p1.setAge(20);
console.log(p1.getAge());
In the code above , All of us age Where properties interact, the related methods must be explicitly called .JavaScript Support the real getter and setter Used to access common data attributes .
stay JavaScript in , There are two ways to define getter and setter.
- Define by object literals , Or in ES6 Of class In the definition of
- By using the built-in Object.defineProperty() Method to define
1、 Define... In object literals getter and setter
- Add... Before the attribute name get Keyword definition getter Method ,getter Method does not accept any parameters
- Add... Before the attribute name set Keyword definition setter Method ,setter Method takes a parameter
- Getting the property value will implicitly call getter Method , Setting a property value will implicitly call setter Method
let obj = {
names: [' Xiao Ming ', ' Xiaohong '],
get firstName() {
console.log(' Get the first person name '); // Some logging can be done
return this.names[0];
},
set firstName(value) {
console.log(' Set the first person name ');
this.names[0] = value;
}
}
console.log(obj.firstName); // hold firstName Operate as an attribute
obj.firstName = ' Little black ';
console.log(obj.firstName);
2、 stay ES6 Of class In the definition of getter and setter
stay “ class ” Can be used internally get and set keyword , Sets the save and value functions for a property , Intercepts the access behavior of this property .
// ES6 Of class Medium getter and setter
class Student {
constructor() {
this.names = [' Xiao Ming ', ' Xiaohong '];
}
get firstName() {
console.log('get firstname');
return this.names[0];
}
set firstName(value) {
console.log('set firstname');
this.names[0] = value;
}
}
let s1 = new Student();
console.log(s1.firstName);
s1.firstName = 'xiaohei';
console.log(s1.firstName);
3、 adopt Object.defineProperty() Definition getter and setter
Don't understand
Object.defineProperty()Students who use this method can read : Property description object - JavaScript course - Net channel
Value function get Parameters... Are not acceptable , Stored value function set Only one parameter can be accepted ( That is, the value of the attribute ).
Case study 1:
var obj = Object.defineProperty({
}, 'p', {
get: function () {
return 'getter';
},
set: function (value) {
console.log('setter: ' + value);
}
});
obj.p // "getter"
obj.p = 123 // "setter: 123"
Case study 2:
function Animal() {
let _age = 2; // You can implement private properties
Object.defineProperty(this,'age',{
get:function () {
console.log('get age');
return _age;
},
set:function (value) {
console.log('set age');
_age = value;
}
})
}
let dog = new Animal();
console.log(dog.age);
dog.age = 4;
console.log(dog.age);
4、 Summary
If an attribute has getter and setter Method , Accessing this property implicitly calls getter Method , Assigning a value to this property will implicitly call setter Method .
For the specified attribute, it is not necessary to define getter and setter. for example , Usually we can only provide getter. If you try to write an attribute value in this case , The specific behavior depends on whether the code is in strict or non strict mode . If in a non strict mode , Yes, only getter Attribute assignment of does not work ,JavaScript The engine silently ignored our request . On the other hand , If I'm in strict mode ,JavaScript The engine will throw an exception , It shows that we are trying to give one only getter No, setter Property of .
Two 、 Use proxies to control access to objects
You can read another blog I wrote :JS Middle agent Proxy Simple use
Front end learning exchange QQ Group , The atmosphere of learning and discussion in the group is very good , There are a lot of big people , Looking forward to your joining :862748629 Click to add
边栏推荐
- [out of distribution detection] deep analog detection with outlier exposure ICLR '19
- The song of cactus - marching into to C live broadcast (2)
- [fundamentals of machine learning 02] decision tree and random forest
- Qt development simple Bluetooth debugging assistant (low power Bluetooth)
- 圣杯布局和双飞翼布局的区别
- Neuron+eKuiper 实现工业物联网数据采集、清理与反控
- [php]tp6 cli mode to create tp6 and multi application configurations and common problems
- Py's optbinning: introduction, installation and detailed introduction of optbinning
- golang調用sdl2,播放pcm音頻,報錯signal arrived during external code execution。
- Dongjiao home development technical service
猜你喜欢

Training penetration range 02 | 3-star VH LLL target | vulnhub range node1

Theory and application of naturallanguageprocessing

leetcode:面试题 08.12. 八皇后【dfs + backtrack】

How can we effectively alleviate anxiety? See what ape tutor says

2022-06-21:golang选择题,以下golang代码输出什么?A:3;B:4;C:100;D:编译失败。 package main import ( “fmt“ ) func

关于solidity的delegatecall的坑

Tableau 连接mysql详细教程

Vue failed to connect to MySQL database

流程引擎解决复杂的业务问题

cookie的介绍和使用
随机推荐
Golang appelle sdl2, lit l'audio PCM et signale une erreur lors de l'exécution externe du Code.
JS中对数组进行去重的几种方法
Introduction to 51 single chip microcomputer - matrix key
Test ofnatural clusters via s-dbscan a self tuning version of DBSCAN
OpenGL - Textures
2022年毕业生求职找工作青睐哪个行业?
Tableau 连接mysql详细教程
The song of cactus - marching into to C live broadcast (1)
Single cell paper record (part6) -- space: spatial gene enhancement using scrna seq
Implement a timer: timer
自定义实现JS中的bind方法
[write CPU by yourself] implementation of exception related instructions
vue连接mysql数据库失败
Error when connecting MySQL with dbeaver for the first time
Literature record (part106) -- graph auto-encoder via neighborhood Wasserstein reconstruction
自然语言处理理论和应用
关于solidity的delegatecall的坑
June training (day 22) - orderly gathering
Error: unable to find vcvarsall Solutions to bat errors
[anomaly detection] malware detection: mamadroid (dnss 2017)