Question

I have 2 prototypes, for the sake of the question, they are:

function Pizza() {
    var aSlice = new PizzaSlice();
    this.extras = [];
    this.addPaproni = function() {
         this.extras.push("paproni");
    }
}

and

function PizzaSlice() { }

Can I call from within PizzaSlice to the function in Pizza so it will issue the addPaproni function on itself?

Meaning, that if I had several Pizza objects, that only the parent of the PizzaSlice that issued the call will have "paproni" in its "this.extras"?

Was it helpful?

Solution

Well, the code cannot infer what the 'parent' is by itself, but you can tell it. I am not sure that I understand how you want your objects to collaborate, but here's an example.

function Pizza() {
}

Pizza.prototype = {
    Pizza: constructor,
    newSlice: function () { return new PizzaSlice(this); },
    addPepperoni: function () { console.log('add pep..'); }
};

function PizzaSlice(pizza) {
    this.pizza = pizza;
    //you can call pizza.whateverYouWant();
}

var pizza = new Pizza(),
    pizzSlice = pizza.newSlice();

OTHER TIPS

You can explicitly bind a function to a certain scope. This might be what you are looking for.

However, the way you have your functions laid out, it seems like this isn't really what you're looking for. What exactly are you trying to do with the PizzaSlice function?

It seems like you might want to use objects instead of functions, and then operate on the objects using functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top