Advertisement
Guest User

Untitled

a guest
Apr 28th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. // Prototypical Model
  2.  
  3. var UserPrototype = {};
  4. UserPrototype.constructor = function(name)
  5. {
  6. this._name = name;
  7. };
  8. UserPrototype.getName = function()
  9. {
  10. return this._name;
  11. };
  12.  
  13. var user = Object.create(UserPrototype);
  14. user.constructor('Joe Bloggs');
  15. console.log('user = ' + user.getName());
  16.  
  17. var AdminPrototype = Object.create(UserPrototype);
  18. AdminPrototype.getName = function()
  19. {
  20. return UserPrototype.getName.call(this) + ' [Admin]';
  21. };
  22.  
  23. var admin = Object.create(AdminPrototype);
  24. admin.constructor('Sally Ann');
  25. console.log('admin = ' + admin.getName());
  26.  
  27. // Classical Model
  28.  
  29. function User(name)
  30. {
  31. this._name = name;
  32. }
  33. User.prototype.getName = function()
  34. {
  35. return this._name;
  36. }
  37.  
  38. var user = new User('Joe Bloggs')
  39. console.log('user = ' + user.getName());
  40.  
  41. function Admin(name)
  42. {
  43. User.call(this, name);
  44.  
  45. var secret = 'Hello';
  46.  
  47. this.getSecret = function(password)
  48. {
  49. return (password === 'cheese')
  50. ? secret
  51. : 'It\'s a secret!';
  52. }
  53. }
  54. Admin.prototype = Object.create(User.prototype);
  55. // Admin.prototype = new User();
  56. Admin.prototype.constructor = Admin;
  57. Admin.prototype.getName = function()
  58. {
  59. return User.prototype.getName.call(this) + ' [Admin]';
  60. };
  61.  
  62. var admin = new Admin('Sally Ann');
  63. console.log('admin = ' + admin.getName());
  64. console.log('secret = ' + admin.getSecret('cheese'));
  65.  
  66. function Student(properties)
  67. {
  68. var $this = this;
  69.  
  70. for (var i in properties) {
  71. (function(i)
  72. {
  73. $this['get' + i] = function()
  74. {
  75. return properties[i];
  76. }
  77. }(i));
  78. }
  79. }
  80.  
  81. var student = new Student({
  82. Name: 'Joe Bloggs',
  83. Age: 24
  84. });
  85. console.log(student.getName());
  86. console.log(student.getAge());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement