Javascript private member on prototype -


Well I tried to figure out that it is possible in any way. Here's the code:

  a = function (text) {var b = text; If (! Arguments.callee.prototype.get) arguments.callee.prototype.get = function () {return b; } Other Alerts ('Already Created!'); } Var c = new a ("test"); // getter var D = creates prototype examples of new A ("ozoz"); // Alert Already Make Alert (CAGT). // Alert Test Alert (D.Jet ()) // Alert Test from context to create prototype function: ( 

As you look, I tried to make prototype greater. If you write something like this:

  a = function (text) {var b = text; this.getText = function () {return B}}  

... everything should be fine .. but really every time I make an object - I get the kind of memory that uses the memory. I have a prototype Ical function is the memory that will do the same ... any thoughts?

Edit:

I tried the solution given by Christopher, and it seems that its for The only known solution should be remembered right now.Id information to get the value from the reference, but the whole idea is good for me :) The only thing to remember the id is, everyone else can be stored once in memory, really M A. You can do a lot of private members store like this, and any time using only an ID. In fact this is satisfying me :) (Until there was no better idea).

someFunc = function () {var store = new Array (); Var guid = 0; Var someFunc = function (text) {this .__ guid = guid; Store [GUID ++] = text; } SomeFunc.prototype.getValue = function () {Return Store [this .__ guid]; } Return to some functions; } () A = new funk ("test"); B = new funk ("test2"); Warning (a.getValue ()); Warning (b.getValue ()); Javascript has not traditionally provided a mechanism for concealment ('private member').

As Javascript, you can always simulate it at the per-object level by defining each manufacturer's methods by using the constructor function as one closure on the individual members, the prototype of the manufacturer T works for the methods defined in the property.

Of course, there are ways to work around this, but I would not recommend it:

This will store your personal property in a different object than your Foo example after destroying delete () Be sure to call: Otherwise, you have also built a memory leak.


Edit 2015 - 12-01: ECMAScript 6 builds improved forms, which do not require manual object destruction, for example one or preferably By using A, to avoid the complete requirement of external stores:

  var Foo = (function () {var bar = symbol ('bar'); function fu () {this [Bar] = 'baz';} Foo.prototype.getBar = function () {return this [bar];} return foo;}) ();  

Comments