Skip to content

Instantly share code, notes, and snippets.

@reconbot
Created February 15, 2011 23:21
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 reconbot/828500 to your computer and use it in GitHub Desktop.
Save reconbot/828500 to your computer and use it in GitHub Desktop.
How would I create a constructor factory?
// 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();
// =(
@reconbot
Copy link
Author

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?

@koudelka
Copy link

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();

@reconbot
Copy link
Author

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