-1

I have an array of objects, and I want to create a method which returns the data inside the method. How do I do this? Thanks

// for example, I have this data
var data = [{ number: 1, name: "Bob" }, { number: 2, name: "Jim" }];

Object.prototype.number = () => {
  // how do I access the object data inside this prototype 
  // i am trying to return something like this, but it doesnt work:
  // return this.number;
};

// i want this to return the number 1
data[0].number();
  ^ 
  | I am trying to access this data in the prototype function and return the number

I know this can be done with data[0].number, but I am trying to do it with an object prototype method.

hello4568
  • 1
  • 1

1 Answers1

3

You need to:

  • Use different property names for the property holding the method and the property holding the data
  • Not use an arrow function (which has lexical this)

// for example, I have this data
var data = [{
  xnumber: 1,
  name: "Bob"
}, {
  xnumber: 2,
  name: "Jim"
}];

Object.prototype.number = function() {
  return this.xnumber;
};

// i want this to return the number 1
console.log(data[0].number());

Note that editing the prototype of built-in objects is considered dangerous.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335