Last active
          April 28, 2016 08:38 
        
      - 
      
 - 
        
Save eddmann/9809926 to your computer and use it in GitHub Desktop.  
    OOP in JavaScript
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // Prototypical Model | |
| var UserPrototype = {}; | |
| UserPrototype.constructor = function(name) | |
| { | |
| this._name = name; | |
| }; | |
| UserPrototype.getName = function() | |
| { | |
| return this._name; | |
| }; | |
| var user = Object.create(UserPrototype); | |
| user.constructor('Joe Bloggs'); | |
| console.log('user = ' + user.getName()); | |
| var AdminPrototype = Object.create(UserPrototype); | |
| AdminPrototype.getName = function() | |
| { | |
| return UserPrototype.getName.call(this) + ' [Admin]'; | |
| }; | |
| var admin = Object.create(AdminPrototype); | |
| admin.constructor('Sally Ann'); | |
| console.log('admin = ' + admin.getName()); | |
| // Classical Model | |
| function User(name) | |
| { | |
| this._name = name; | |
| } | |
| User.prototype.getName = function() | |
| { | |
| return this._name; | |
| } | |
| var user = new User('Joe Bloggs') | |
| console.log('user = ' + user.getName()); | |
| function Admin(name) | |
| { | |
| User.call(this, name); | |
| var secret = 'Hello'; | |
| this.getSecret = function(password) | |
| { | |
| return (password === 'cheese') | |
| ? secret | |
| : 'It\'s a secret!'; | |
| } | |
| } | |
| Admin.prototype = Object.create(User.prototype); | |
| // Admin.prototype = new User(); | |
| Admin.prototype.constructor = Admin; | |
| Admin.prototype.getName = function() | |
| { | |
| return User.prototype.getName.call(this) + ' [Admin]'; | |
| }; | |
| var admin = new Admin('Sally Ann'); | |
| console.log('admin = ' + admin.getName()); | |
| console.log('secret = ' + admin.getSecret('cheese')); | |
| function Student(properties) | |
| { | |
| var $this = this; | |
| for (var i in properties) { | |
| (function(i) | |
| { | |
| $this['get' + i] = function() | |
| { | |
| return properties[i]; | |
| } | |
| }(i)); | |
| } | |
| } | |
| var student = new Student({ | |
| Name: 'Joe Bloggs', | |
| Age: 24 | |
| }); | |
| console.log(student.getName()); | |
| console.log(student.getAge()); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment