0

I want function to be available on a object, but I don't it to be visible if if I console.log it or send it to another function.

var obj = function() {
  this.name = 'Bob';
  this.age = 23;
}
obj.prototype.say = function() {
  console.log(this.name, this.age, 'thats me..');
}

var pers = new obj();
console.log(pers); // { name: 'Bob', age: 23 } 
pers.say(); // Bob 23 thats me..

Would this be good for solution and good practice for that? Or is it a better way to accomplish this in javascript?

RickBrunstedt
  • 1,921
  • 2
  • 12
  • 12

1 Answers1

0

Functions created by using prototype would also be visible when you log the object. The only thing you can do at this context is to create functions in your constructor using this and create a closure. And these functions will not be a shared functions among the object instances unlike prototypal functions. I mean, the function's change will not be reflected in all object instances.

var obj = function() {
  this.name = 'Bob';
  this.age = 23;
  function privateTest(){ alert("hai"); }
  this.test = privateTest;
}
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130