JavaScript Encapsulation -
So I'm looking at full development object-oriented JavaScript practices and think about the following examples.
As I understood it, (and it makes sense to me) that the following 'secret' field is 'private':
var MyObject = function () {Var secret = 'sshhh'; This.getSecret () = function () {return secret; }}
And the reason for this is that there is an area of work in the regional secret that can use the internal function, but nothing outside of it ... so far is good.
But I have seen 'around the following (and in particular Douglas Crockford's book):
var MyObject = function () {var secret =' sshhh '; Return {getSecret: function () {return secret; }}} ();
And wondering what the difference is, why is it better? I understand that in this case we are not returning the same object, which is present in the private sector, but does not seem to be a big advantage because you can not reach this area directly in any way.
These examples are very different ... first a "MyObject" function
When it is called, using the constructor, new
, a "getSecret" function
will be in the form of a property; Second, "MyObject" creates a object
as a property in the form of a "getSecret" function
.
In that respect, it is like the difference between a statutory law and a public law in the first case, only when the producer is asked, not only in the constructor. In the second case there is no constructor.
So assume that you have:
var MyObject1 = function () {var secret = 'sshh'; This.getSecret = function () {return secret; }} // ... var MyObject2 = function () {var secret = 'sshhh'; Return {getSecret: function () {return secret; }}} ();
Run some tests:
MyObject1.getSecret (); // TypeError: There is no way in the object 'getSecret' var m1 = new MyObject1 (); M1.getSecret (); // "sshhh" MyObject2.getSecret (); // "sshhh" var M2 = new MyObject2 (); // TypeError: Object function is not
So MyObject1 is like a square, and MyObject2 is like a stable class.
Comments
Post a Comment