0

When I managed to define a function inside prototype object, but when I use foreach loop on the props I found this method as one of my props either.

I wanted to know if I can define methods like the toString() mehtod?

the hasOwnProperty() if inside the loop is not an option for me because the loop is inside a package.

Here is my code.

function Person (personProps) {

    Object.assign(this, {...personProps});
    console.log(this);
}

Person.prototype.sayHay = () => {
    console.log("hay");

}


const createPerson = (personProps) => {
    let x = new Person(personProps);
    x.sayHay();
    return x;
};

export default createPerson;

Thanks for helping.

Hassaan
  • 3,931
  • 11
  • 34
  • 67
Goor Lavi
  • 412
  • 3
  • 16

2 Answers2

1

You can define property on the Person prototype like so -

function Person(personProps) {
  Object.assign(this, { ...personProps});
}

Object.defineProperty(Person.prototype, "sayHay", {
  value: function() {
    console.log("hay");
  },
  /* 
     You can make `enumerable` property below false, 
     if you don't want it to be shown while 
     looping over properties
  */
  enumerable: true 
});

const createPerson = (personProps) => {
  let x = new Person(personProps);
  return x;
};

let person = createPerson({
  a: 1
})

person.sayHay();

for (p in person) {
  console.log(p);
}

This way you don't have to define sayHay property each time you create the object.

Yasser Hussain
  • 854
  • 7
  • 21
0

You can use a class

class Person {
  constructor(personProps) {
    Object.assign(this, { ...personProps});
  }

  sayHay() {
    console.log("hay");
  }
}

const createPerson = (personProps) => {
  let x = new Person(personProps);
  x.sayHay();
  return x;
};

let person = createPerson({
  name: 'John'
});

for (prop in person) {
  console.log(prop);
}
Serge K.
  • 5,303
  • 1
  • 20
  • 27
  • my problem in this solution is that i dont want the Person to have functions refs. and also i need to send does Persons to the server side without the functions – Goor Lavi Aug 16 '17 at 13:41
  • 1
    _"i dont want the Person to have functions refs."_ What do you mean ? – Serge K. Aug 16 '17 at 13:51
  • oh im sorry. i ment i want the Person to have functions references*. i dont want a function per instance – Goor Lavi Aug 16 '17 at 13:55
  • Not sure what you mean, but look at @evolutionxbox comment, it should guide you to another solution – Serge K. Aug 16 '17 at 13:57
  • 2
    @GoorLavi Using a `class` doesn't create a function per instance. It's still on the prototype, just not enumerable by default. – Bergi Aug 16 '17 at 17:32