sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

Internal private property access failure from constructor #102

Closed Ravenex closed 5 years ago

Ravenex commented 5 years ago

The code:

const ObjectModel = require('objectmodel').ObjectModel

class Dad extends ObjectModel({ _loaded: Object, ID: String, USER_ID: Number }) {

  constructor(data) {
    data._loaded = {}
    super(data)
    this._loaded['daughter'] = {
      ids: null
    }
  }

}

try{ new Dad({ ID: 'Dad', USER_ID: 5 }) } catch(err){console.log(err)}

results in:

TypeError: cannot access to private property _loaded
    at new Dad (C:\Users\Ravenex\Documents\test\error.js:8:10)
    at Object.<anonymous> (C:\Users\Ravenex\Documents\test\error.js:15:6)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
sylvainpolletvillard commented 5 years ago

Actually this is the intended behaviour. Private access is granted only from the model own methods. Here you are extending the model with a class, Dad. The class constructor is not a method of the model, so private access is not granted.

The basic idea of private properties is that they should not be used outside of the model. So you should probably add a method to the model to handle this part. There is no "private/protected" distinction like in Java.

Technically, it is impossible to grant private acccess from a extended class constructor or method, because these functions run completely out of reach of ObjectModel interceptors ; that as their name suggests, only applies on Model properties.

Ravenex commented 5 years ago

That is fine, I can do this without the constructor, I actually found this while trying to simplify the file for the other error I posted. If this is intended then no problem.

sylvainpolletvillard commented 5 years ago

Okay, I close the issue then