Skip to content

Instantly share code, notes, and snippets.

@jqtrde
Last active December 14, 2015 07:19
Show Gist options
  • Save jqtrde/5049693 to your computer and use it in GitHub Desktop.
Save jqtrde/5049693 to your computer and use it in GitHub Desktop.
The worst piece on constructors you'll ever read.
// Javascript constructors!
// A constructor is just a plain old function that's invoked with the `new`
// operator, and which produces a specialized object. Useful when you have
// many similar objects.
// Here, `Person` is a constructor.
function Person(name, nickname, age) {
this.name = name;
this.nickname = nickname;
this.age = age;
};
// And we can use it to create new objects!
broOne = new Person('Jacques Tardie', 'Gwak', 25);
console.log(broOne);
// broOne is now an `instance` of Person
console.log(broOne instanceof Person); // true
// If you had created another object, without using the constructor:
broTwo = {
'name': 'Jim Bob',
'nickname': 'Jasmine',
'age': 100
};
// then it won't be an instance of Person.
console.log(broTwo instanceof Person); // false
// Things being instances of things, means that you can add a method
// to the prototype of the constructor, and all it's instances will inherit
// from it.
Person.prototype.sup = function() {
greeting = 'Sup, its your boy ' + this.nickname;
return greeting;
};
console.log(broOne.sup()); // Sup, it's your boy Gwak
// Kewl. Except when you forget the `new` you're supposed to add before the
// constructor.
// When you forget the `new`, the `this` defaults to the standard `this`
// that functions get, which is usually `window` in the browser, or `global` in
// node.
globalthing = 'bubrub';
function Constructinator(yes, no, globalthing) {
this.yes = yes;
this.no = no;
this.globalthing = globalthing;
};
badBoi = Constructinator('yeash', 'nah', 'hubbahhubbah'); // BAD, NO NEW!
console.log(globalthing); // = hubbahhubbah. Supposed to equal bubrub!
console.log(badBoi); // undefined
// So, you just changed the globalthing from 'bubrub', to 'hubbahhubbah',
// which I think we can all agree is bad.
//
// Plus, your badBoi instance is undefined.
//
// So, what are your options? You know your coworker is going to forget the
// `new`.
// TEST YO CONSTRUCTOR.
function Winning(a, b) {
if (this instanceof Winning) {
this.a = a;
this.b = b;
} else {
throw new Error('FORGOT YOUR NEW');
};
};
good = new Winning('pablo', 'escobar'); // { a: 'pablo', b: 'escobar' }
bad = Winning('Your', 'neighbor'); // Error: FORGOT YOUR NEW
// Amen.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment