Devin Dixon
Devin Dixon

Reputation: 12403

Accessing JS Private Methods

I am working on trying to make an JS object and access to private methods. The problem I am running into when trying to return a function is the private methods cannot be accessed. Code Below.

var Item = (function() {

    var price = 0;
    var name = '';
    var description = '';
    var quantity = '';
    var attributes = {};

    var Item = function(data) {

    }

    function setPrice(variable) {
        this.price = variable;
    };

    function getPrice() {
        return this.price;
    };

    function setName(variable) {
        this.name = variable;
    };

    function getName() {
        return this.name;
    };

    function setDescription(variable) {
        this.description = variable;
    };

    function setQuantity(variable) {
        this.quanity = variable;
    };

    return function(data){

        setPrice : setPrice;
        getPrice : getPrice;
        setName : setName;
        setDescription : setDescription;
        setQuantity : setQuantity;

        return new Item(data);
    }

})();

item2 = Item();
    item2.setPrice('3');
alert(item2.getPrice());

With this setup, how can I access the private methods?

Upvotes: 0

Views: 147

Answers (2)

bPratik
bPratik

Reputation: 7019

Fixed your code here: http://jsfiddle.net/pratik136/JryAk/

Items changed:

  • Check your return statement
  • Item is a var, you were trying to instantiate a class object item2

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

I don't think that pattern will work for what you're trying to do. I think using a pattern like this one will keep your code smaller and more reusable. This way you also get rid of the set functions.

var Item = function(options) {

    var opts = $.extend({
        price: 0,
        name: '',
        description: '',
        quantity: '',
        attributes: {}
    }, options);

    // ...
    this.getPrice = function() {
        return opts.price;
    };

    // ...
};

var item = new Item({
    price: 100,
    name: 'onehundred',
    // ...
});

alert(item.getPrice());

Upvotes: 2

Related Questions