Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:04
Show Gist options
  • Save svanellewee/73ea1e4e2d6631f08a59 to your computer and use it in GitHub Desktop.
Save svanellewee/73ea1e4e2d6631f08a59 to your computer and use it in GitHub Desktop.
New vs Object.create
var pp = console.log
var Person = { name : "Frank Cadillac",
greet: function() { return "Hello world, my name is "+this.name+"!!!";}
}
// does not work!
// Person.prototype.getName = function(){
// return this.name;
// }
var frank0 = Object.create(Person);
pp(frank0.greet());
//pp(frank.getName());
pp(Person.prototype)
// now with functions
//pp(frank instanceof Person)
function Mammal(name) {
this.name = name || "Lebowski";
}
Mammal.prototype.greet = function () { return "Mr "+this.name+" says 'WOA MAN, BEVERAGE!'" }
var dude = new Mammal("The Dude")
pp(dude.greet());
pp(Mammal.prototype)
pp(dude instanceof Mammal)
function Politician(name) {
Mammal.apply(this, [name]);
this.name = this.name || "Douche McNonsenson"; // family name
}
Politician.prototype = new Mammal("MEGATRON!"); // for president
var frank = new Politician("Frank Underwood");
pp(frank.greet())
pp(Politician.prototype.name)
function create(o) {
function F() {};
F.prototype = o;
return new F();
}
var robert = create(new Mammal("OPTIMUS"))
pp(robert.greet())
robert.surname = "Prime";
robert.getSurname = function() { return this.surname+"!!!!" }
pp(robert.getSurname())
var joe = create(robert);
joe.location = "here";
joe.getLocation = function() { return this.location+", which is a nice place" }
pp(joe.getLocation())
pp(joe.getSurname())
/*
~/source/nodejs$ node oop.js
Hello world, my name is Frank Cadillac!!!
undefined
Mr The Dude says 'WOA MAN, BEVERAGE!'
{ greet: [Function] }
true
Mr Frank Underwood says 'WOA MAN, BEVERAGE!'
MEGATRON!
Mr OPTIMUS says 'WOA MAN, BEVERAGE!'
Prime!!!!
here, which is a nice place
Prime!!!! */
@svanellewee
Copy link
Author

the whole point of prototypal inheritance is that you are inheriting from other objects.

Object.create/ create needs to be passed an object of some kind.
Remember Functions are first class objects in js

Also remember the prototype chain! (joe --> robert --> new Mammal("OPTIMUS"); )

So in essence Object.create just helps to create that prototype chain!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment