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?

1
  • This doesn't make it invisible I think. Just click on the "prototype" tag if you're on chrome Commented Apr 4, 2016 at 8:57

1 Answer 1

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

3 Comments

@NinaScholz But privateTest would not be visible. That is the point here.
When i logg your solution (I'm running node if that matter) I get: { name: 'Bob', age: 23, test: [Function: privateTest] }
@user3688556 That is fine. But you will not have control over privateTest

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.