当前位置:网站首页>Access to control objects in JS

Access to control objects in JS

2022-06-22 07:00:00 webchang


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

原网站

版权声明
本文为[webchang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220651063398.html