Guest User

Encapsulation in javascript

a guest
Feb 28th, 2012
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. SomeClass = function(id) {
  2. this._id = id;
  3. }
  4. (function() {
  5. function intFun() {
  6. return this._id;
  7. }
  8. SomeClass.prototype.extFun = function() {
  9. return incFun();
  10. }
  11. })();
  12.  
  13. SomeClass = function (id) {
  14. var THIS = this; // unambiguous reference
  15. THIS._id = id;
  16.  
  17. var intFun = function () { // private
  18. return THIS._id;
  19. }
  20.  
  21. this.extFun = function () { // public
  22. return intFun();
  23. }
  24. }
  25.  
  26. MyClass = function(x, y, z) {
  27. // This is the constructor. When you use it with "new MyClass(),"
  28. // then "this" refers to the new object being constructed. So you can
  29. // assign member variables to it.
  30. this.x = x;
  31. ...
  32. };
  33. MyClass.prototype = {
  34. doSomething: function() {
  35. // Here we can use the member variable that
  36. // we created in the constructor.
  37. return this.x;
  38. },
  39. somethingElse: function(a) {
  40. }
  41. };
  42.  
  43. var myObj = new MyClass(1,2,3);
  44. alert(myObj.doSomething()); // this will return the object's "x" member
  45. alert(myObj.x); // this will do the same, by accessing the member directly
  46.  
  47. myDiv.onclick = myObj.doSomething;
  48.  
  49. myDiv.onclick = function() {
  50. myObj.doSomething.call(myObj);
  51. }
  52.  
  53. var MyClass = function() {};
  54.  
  55. MyClass.prototype = {
  56. _someVar : null,
  57. _otherVar : null,
  58.  
  59. initialize: function( optionHash ) {
  60. _someVar = optionsHash["varValue"];
  61. _otherVar = optionsHash["otherValue"];
  62. },
  63.  
  64. method: function( arg ) {
  65. return _someVar + arg;
  66. },
  67. };
  68.  
  69. var myClass = new MyClass( { varValue: -1, otherValue: 10 } );
  70. var foo = myClass.method(6);
Add Comment
Please, Sign In to add comment