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?

4
  • 1
    There are no private methods in js. Why would you want to make one? Commented Aug 10, 2015 at 14:13
  • 1
    @Bergi because I don't want anyone call the method outside Commented Aug 10, 2015 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: github.com/getify/You-Dont-Know-JS You can read all about this stuff! Commented Aug 10, 2015 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. Commented Aug 10, 2015 at 14:22

1 Answer 1

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

6 Comments

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.
Bumping this answer as this shows a simple but clean example of a closure in javascript.
I think by doing this, every instance will contain a copy of the method, right? how can I avoid this
Also, this doesn't work within the privateFunction if it's called like this.
@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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.