Skip to content

Instantly share code, notes, and snippets.

@JNaftali
Last active August 24, 2017 19:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JNaftali/388ab14b996e592a783f58162d6cf47f to your computer and use it in GitHub Desktop.
Save JNaftali/388ab14b996e592a783f58162d6cf47f to your computer and use it in GitHub Desktop.
Factory/Module pattern of OOJS
function createTeacher(name, age, secret, position) {
var result = createPerson(name, age, secret, position);
result.teach = function() {
return 'i am teaching stuff kinda sorta';
};
result.position = position;
return result;
}
function createPerson(name, age, secret) {
secret = secret || 'everybody has a secret';
return {
name: name,
get age() {
return age;
},
birthday: function() {
return (age += 1);
},
secretLength: function() {
return secret.length;
},
};
}
//
//
//
//
//
//
var josh = createPerson('josh', 30, 'I have small hands');
console.log(josh);
console.log('testing birthday function');
console.log('age is', josh.age);
josh.birthday();
console.log('age is', josh.age);
console.log('testing setting age directly');
console.log('age is', josh.age);
josh.age = 5;
console.log('age is', josh.age);
console.log('testing setting name directly');
console.log('name is', josh.name);
josh.name = 'butts';
console.log('name is', josh.name);
console.log('testing secretLength function');
console.log(josh.secretLength());
console.log('testing accessing secret directly');
console.log('secret is', josh.secret);
function Person(name, age, secret) {
this.name = name;
this.age = age;
this.secret = secret || 'everybody has a secret';
}
Person.prototype.birthday = function birthday() {
return (this.age += 1);
};
Person.prototype.secretLength = function secretLength() {
return this.secret.length;
};
//
//
//
//
//
//
//
//
var josh = new Person('josh', 30, 'I have small hands');
console.log(josh);
console.log('testing birthday function');
console.log('age is', josh.age);
josh.birthday();
console.log('age is', josh.age);
console.log('testing setting age directly');
console.log('age is', josh.age);
josh.age = 5;
console.log('age is', josh.age);
console.log('testing setting name directly');
console.log('name is', josh.name);
josh.name = 'butts';
console.log('name is', josh.name);
console.log('testing secretLength function');
console.log(josh.secretLength());
console.log('testing accessing secret directly');
console.log('secret is', josh.secret);
//if you forget the new keyword, bad things happen
// var josh = Person('josh', 30);
// console.log(josh, name, age);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment