How to add custom methods to a Model?
DaviidMM opened this issue · 1 comments
DaviidMM commented
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
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()