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

4
  • 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. Commented Oct 19, 2020 at 13:12
  • Creating a User class can be done, this resource can be useful: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 19, 2020 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? Commented Oct 19, 2020 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 Commented Oct 19, 2020 at 13:49

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

3 Comments

or get isMale() {... and then call with carlos.isMale
Thanks for the answer. Can we do it globally for all the object?
@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.
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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.