Skip to content

Instantly share code, notes, and snippets.

@eddmann
Last active April 28, 2016 08:38
Show Gist options
  • Select an option

  • Save eddmann/9809926 to your computer and use it in GitHub Desktop.

Select an option

Save eddmann/9809926 to your computer and use it in GitHub Desktop.

Revisions

  1. eddmann created this gist Mar 27, 2014.
    86 changes: 86 additions & 0 deletions oop.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,86 @@
    // 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());