0

Assume I make a custom Object:

function MyObject() {
  // define some properties
}

Now I want define a private method in the prototype:

MyObject.prototype = {
  // by doing this I defined a public method, how can I define a private method?
  myMethod: function() {
    //some code
  }
}

Then I want to call the function in the constructor like this:

function MyObject() {
  // define some properties
  call myMethod()
}

How can I do it?

Jason Geiger
  • 1,912
  • 18
  • 32
Brick Yang
  • 5,388
  • 8
  • 34
  • 45
  • 1
    There are no private methods in js. Why would you want to make one? – Bergi Aug 10 '15 at 14:13
  • 1
    @Bergi because I don't want anyone call the method outside – Brick Yang Aug 10 '15 at 14:14
  • Try `this.myMethod()`. When creating a class and an instance of that class with the `new` keyword the object gets prototyped linked. `this` will refer to the current instance of that class. An awesome book series going pretty in depth and FREE is: https://github.com/getify/You-Dont-Know-JS You can read all about this stuff! – Jens Aug 10 '15 at 14:15
  • @BrickYang: Then just tell everyone they should not use it. Of course you can always define and call local functions if you need them; but *methods* are always public in js. – Bergi Aug 10 '15 at 14:22

1 Answers1

2

If you want a private method, don't use the prototype. Make use of function scope instead:

function MyObject() {

  var privateFunction = function () {
      // only code within this constructor function can call this
  };

  privateFunction();
}
sma
  • 9,449
  • 8
  • 51
  • 80
  • This is pretty much the only way to do private functions in js. Worth noting explicitly that other functions on the object prototype cannot call the function either, and you'll get a copy of the function in memory per instance rather than having one function shared across all instances, as with functions defined on the prototype. – James Thorpe Aug 10 '15 at 14:17
  • Bumping this answer as this shows a simple but clean example of a closure in javascript. – Jens Aug 10 '15 at 14:18
  • I think by doing this, every instance will contain a copy of the method, right? how can I avoid this – Brick Yang Aug 10 '15 at 14:22
  • Also, `this` doesn't work within the `privateFunction` if it's called like this. – Bergi Aug 10 '15 at 14:23
  • @BrickYang: Just move the declaration outside of the `MyObject` function. Of course it'll loose its access to closure variables by that, but you don't seem to have any – Bergi Aug 10 '15 at 14:24
  • @Bergi Thanks. This is exactly what I did. But I wanna avoid much copies so I tried prototype then I lost the "private". Seems I just can't have my cake and eat it. – Brick Yang Aug 10 '15 at 14:30