Last active
August 29, 2015 14:04
-
-
Save svanellewee/73ea1e4e2d6631f08a59 to your computer and use it in GitHub Desktop.
New vs Object.create
This file contains 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
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!!!! */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!