Created
February 15, 2011 23:21
-
-
Save reconbot/828500 to your computer and use it in GitHub Desktop.
How would I create a constructor factory?
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
// http://oranlooney.com/functional-javascript/ | |
function Clone() { } | |
function clone(obj) { | |
Clone.prototype = obj; | |
return new Clone(); | |
} | |
Food = function(type, slices){ | |
this.type = type; | |
this.slices= slices; | |
this.eat= function(){ | |
this.slices --; | |
console.log('I ATE 1 Slice I have ' + this.slices + " left!"); | |
} | |
this.status = function(){ | |
console.log(this, 'I am a ' + this.type + ' and I have ' + this.slices + " slices."); | |
} | |
this.toppings = {}; | |
} | |
Pizza = new Food('pizza', 8); | |
Pizza.status(); | |
my_pizza = clone(Pizza); | |
my_pizza.status(); | |
my_pizza.eat(); | |
my_pizza.status(); | |
Pizza.status(); | |
// But what about the DEEP toppings object? | |
my_pizza.toppings.peperoni = 'OH GOD YES'; | |
my_pizza.status(); | |
Pizza.status(); | |
// =( |
How about this? :)
Food = function(b) {
return function() {
console.log('running');
this.type = b.type;
this.callback = b.callback;
this.eat = function(){
console.log('I ATE ' + b.type + ', ' + this.slices + ' slices');
this.callback();
}
}
}
foo = function(){console.log('I got called');}
Pizza = new Food({'type':'pizza', 'callback': foo});
//Pizza.eat(); // Dont want to eat the global pizza...
my_pizza = new Pizza();
my_pizza.slices = 5
my_pizza.eat();
your_pizza = new Pizza();
your_pizza.slices = 1
your_pizza.eat();
I did what I think is a shallow clone - a prototype inheritance http://oranlooney.com/functional-javascript/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want to make pizzas for EVERYONE so they have their own pizzas!
I can't make a new Pizza() because Pizza is not a constructor - can I clone it or something?