Accessing JS Private Methods

前端 未结 2 1655
渐次进展
渐次进展 2020-12-22 10:48

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 ac

相关标签:
2条回答
  • 2020-12-22 11:14

    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
    0 讨论(0)
  • 2020-12-22 11:28

    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());
    
    0 讨论(0)
提交回复
热议问题