sylvainpolletvillard / ObjectModel

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

How to add custom methods to a Model? #152

Closed DaviidMM closed 1 year ago

DaviidMM commented 2 years ago

Using for example a ObjectModel, how can I add method or functions to it?

In the following example, how can I add or create the method getColor() so it returns thecolor property of the object davidm ?

const Person = ObjectModel({
  name: String,
  color: String
})

const davidm = Person({
  name: 'David',
  color: 'red'
})

console.log(davidm.getColor())

Thank you beforehand 😄

sylvainpolletvillard commented 1 year ago

Sorry for the late answer,

You can add methods through prototypal delegation in JavaScript. Models are the constructors of your objects:

const Person = ObjectModel({
  name: String,
  color: String
})

Person.prototype.getColor = function(){
  return this.name
}

const davidm = Person({
  name: 'David',
  color: 'red'
})

console.log(davidm.getColor())

You can also use the class operator:

class Person extends ObjectModel({
  name: String,
  color: String
}){
    getColor(){
        return this.color 
    }
}

const davidm = new Person({
  name: 'David',
  color: 'red'
})

davidm.getColor()