Glyph
Glyph

Reputation: 555

How can I avoid using eval() for the base object

As I understand it, eval() can be harmful. And it's annoying seeing all the warnings in my JSLint.

I've got a number of functions that are identical for my Wishlist / Shopping Cart. So I'd like to make it dynamic and only have one function of each.

Instead of cart.addItem() and wish.addItem(), I want cartWish.addItem(type).

Inside of cartWish.addItem() I need to access cart.data or wish.data, depending on the type argument.

How can I do this without resorting to eval(type).data?

I tried this[type].data and it didn't seem to work right.

Upvotes: 0

Views: 107

Answers (2)

Glyph
Glyph

Reputation: 555

It was poor programming on my part. I didn't know that JavaScript tended to make references of objects instead of copies.

So doing...

var myReference=(type == "cart") ? cart.data : wish.data;
myReference[0].name="Bob Dole's Grill";

... will actually change cart.data[0].name outside of the function. And it will do so without making a copy of the cart object in memory.

Note: You could also just pass in the object by reference into the function, but I'm not sure if I can, because I'm sometimes invoking this function from a KnockoutJS click event.

Upvotes: 0

Greg Burghardt
Greg Burghardt

Reputation: 18783

What's the difference between

cart.addItem(...);
wish.addItem(...)

and

cartWish.addItem("cart", ...);
cartWish.addItem("wish", ...);

Seems like the same number of lines of code, and then all you've done is obfuscate what you are really doing. Maybe create a function that takes either a cart or wish object and assume they have the same interface:

function addItem(x, data) {
    x.addItem(data);
}

var cart = ...
var wish = ...

addItem(cart, {...});
addItem(wish, {...});

Another option is to create a class:

function Item(type) {
    this.type = type;
}

Item.prototype.add = function add(...) {
    // ...
};


var cart = new Item("cart");
var wish = new Item("wish");

cart.add(...)
wish.add(...)

Upvotes: 1

Related Questions