0

I have an Object which I am getting from API response. Now I want to perform some operation on that object and I want to do it in prototype way.

let's say I am getting following object

const user = {
 name: "Carlos",
 gender: "male"
}

Now I want to create a prototype function which can run directly on object like. user.isMale()

how can I achieve the same in ES6

Jitender
  • 7,593
  • 30
  • 104
  • 210
  • 2
    Are you sure you want to change the global Object prototype and add an `isMale` method to *every* object? It would make more sense to create a `User` *class*. – Quentin Oct 19 '20 at 13:12
  • Creating a `User` class can be done, this resource can be useful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – jbmusso Oct 19 '20 at 13:13
  • @Quentin: yeah right it makes more sense to create a User class but just for curiosity how can we do it globally? – Jitender Oct 19 '20 at 13:27
  • If you want to do this because the object is already created, like, for example by `JSON.parse(json)`, then you can either `carlos = Object.assign(new User(), JSON.parse(json))` or you can `Object.setPrototypeOf(carlos = JSON.parse(json), User.prototype)`. See [this answer](https://stackoverflow.com/a/43977474/1563833) – Wyck Oct 19 '20 at 13:49

2 Answers2

3

I would recommend to use es6 classes

class User{
    constructor(user = {}){
        this.name = user.name;
        this.gender = user.gender;
    }

    isMale(){
        return this.gender === 'male';
    }
}

let carlos = new User({'carlos', 'male'})

carlos.isMale() // true

and if you retrieve an array of those users you could then map them in this way.

usersArray = usersArray.map(user => new User(user));
toms
  • 515
  • 6
  • 23
  • 1
    or `get isMale() {`... and then call with `carlos.isMale` – Wyck Oct 19 '20 at 13:22
  • Thanks for the answer. Can we do it globally for all the object? – Jitender Oct 19 '20 at 13:27
  • 3
    @Carlos, doing it globally for all objects would be a **terrible** idea, but technically possible with `Object.prototype.isMale = function() { return this.gender === 'male' }`. Another **terrible** idea would be to replace each object's prototype after it is created (slower) with `Object.setPrototypeOf(someUserObject, User.prototype)`. Better idea is to ensure each User object is created with `new User`, and therefore gets the right prototype when it is created. – Wyck Oct 19 '20 at 13:37
0

function User(name, gender) {
  this.name = name;
  this.gender = gender;
}

User.prototype.isMale = function() {
  return this.gender === 'male';
}

const user = new User('john', 'male');
alert(user.isMale());