Skip to content

Instantly share code, notes, and snippets.

@jgautier
Created March 9, 2011 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgautier/861767 to your computer and use it in GitHub Desktop.
Save jgautier/861767 to your computer and use it in GitHub Desktop.
Settign the .prototype property
//create object with function
var Foo=function(){
};
//set the bar method on the prototype
Foo.prototype={
bar:function(){
console.log("bar");
}
};
var foo=new Foo();
//change Foo's prototype
Foo.prototype={
bar:function(){
console.log("overriden bar");
}
};
//overridden bar? NO!
foo.bar();
//set it using the __proto__
foo.__proto__.bar=function(){
console.log("overriden bar");
};
//success!
foo.bar();
//set it using getPrototypeOf
Object.getPrototypeOf(foo).bar=function(){
console.log("getPrototypeOf() bar");
};
//success!
foo.bar();
//define an Animal object
var Animal=function(){
};
//all Animals gotta eat
Animal.prototype={
eat:function(){
console.log("nom nom nom");
}
};
var Human=function(){
};
//a Human is an Animal
Human.prototype=Animal.prototype;
var Cat=function(){
};
//a Cat is an Animal
Cat.prototype=Animal.prototype;
var Dog=function(){
};
//a Dog is an Animal
Dog.prototype=Animal.prototype;
//create instances of each type
var julian=new Human();
var rover=new Dog();
var whiskers = new Cat();
//we can all eat
julian.eat();
rover.eat();
whiskers.eat();
//we are all animals
console.log(julian instanceof Animal);
console.log(rover instanceof Animal);
console.log(whiskers instanceof Animal);
//create object with function
var Foo=function(){
//create a method directly in the object
this.baz=function(){
console.log("baz");
};
};
//you can set the prototype with a single call using an object literal
Foo.prototype={
bar:function(){
console.log("bar");
}
};
//you can set the a single property of the prototype using dot notation
Foo.prototype.bar=function(){
console.log("bar");
};
//you can set the prototype with racket notation
Foo.prototype["bar"]=function(){
console.log("bar");
};
//create instance of Foor
var foo=new Foo();
//baz is defined on the object and requires no delegation
foo.baz();
//bar is defined on Foo's prototype. Foo looks bar up directly on itself its not found so it looks it up on its prototype
foo.bar();
//create object with function
var Foo=function(){
this.bar=function(){
console.log("direct bar");
};
};
//set the bar method on the prototype
Foo.prototype={
bar:function(){
console.log("prototype bar");
}
};
Foo.prototype.__proto__.bar=function(){
console.log("_proto__ bar");
};
var foo=new Foo();
foo.bar();//== "direct bar"
//delete the bar function from foo
delete foo.bar;
foo.bar();//== "prototype bar"
//delete bar from Foo's prototype
delete Foo.prototype.bar;
foo.bar();//== "__proto__ bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment