Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Object Property

I am playing with ES6 classes and to better manage an array property of the class, I replaced the array with an object and added all the array-related functions (get, add, remove, etc) along with an array sub-property:

class MyClass {
constructor () {
    this.date_created = new Date()
}
posts = {
    items: [],
    get: () => {
        return this.posts.items
    },
    add: (value) => this.posts.items.unshift(value),
    remove: (index) => this.posts.items.splice(index, 1)
}
}

So it got me thinking: is there a way to setup that posts object to return the items array by default? i.e. through: MyClass.posts I thought I could trick it with the get() but didn't work.

like image 875
xon52 Avatar asked Sep 13 '26 20:09

xon52


1 Answers

If you want to keep the actual array hidden and untouchable except through the methods, it has to be declared in the constructor. Any function that alters it has to be declared in the constructor as well. If that item is to be publicly accessible, it has to be attached to this.

class Post extends Array
{
  add(val)
  {
    this.unshift(val);
  }
  remove()
  {
    this.shift();
  }
}

class MyClass 
{
  constructor() 
  {
    this.date_created = new Date()
    
    this.post = new Post();
  }
}
let x = new MyClass();
console.log(x.post);
x.post.add(2);
console.log(x.post);
like image 108
Eddie D Avatar answered Sep 16 '26 09:09

Eddie D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!