Javascript OOP 私有函数

Javascript OOP private functions

我想创建一个构造函数,它可以用 json 文件实例化,然后由一些私有函数使用,最后将它们的结果传递给原型的 public 函数.这是正确的方法吗?

这里有更具体的代码:

//constructor
function queryArray(json){
    this.json = json;

    //init qry template with default values
    function qryInit() {
        var qryTemplate = {
            //some stuff
        }
        return qryTemplate;
    }

    //generate array of request templates
    function qryTempArray(json){
        var template = qryInit();
        var qryTempArray1 = [];
        for(var i = 0; i < json.length; i++){
            qryTempArray1.push({
                'SearchIndex': json[i].SearchIndex,
                'Title': json[i].Title,
                'Keywords': json[i].Keywords,
                'MinimumPrice': json[i].MinimumPrice,
                'MaximumPrice': json[i].MaximumPrice,
                'ResponseGroup': template.ResponseGroup,
                'sort': template.sort
            });
        }
        return qryTempArray1;
    }
}

//function for finally building all the queries
queryArray.prototype.qryBuilder = function(){
    var qryTempArray1 = [];
    qryTempArray1 = qryTempArray(this.json);
    //other stuff
}

如果我在一个对象上调用 qryBuilder 函数,我得到一个错误 在 for 循环(未定义)中 json.length 处的函数 qryTempArray 中。 为什么?

正如上面所写的代码,令我惊讶的是您竟然进入了循环。当您调用 qryBuilder(); 时,您似乎会变得不确定。 我希望按照以下方式工作。

//constructor
function queryArray(json) {
    var self = this;
    self.json = json;

    //init qry template with default values
    self.qryInit = function() {
        var qryTemplate = {
            //some stuff
        }
        return qryTemplate;
    }

    //generate array of request templates
    self.qryTempArray = function(json) {
        var template = self.qryInit();
        var qryTempArray1 = [];
        for (var i = 0; i < json.length; i++) {
            qryTempArray1.push({
                'SearchIndex': json[i].SearchIndex,
                'Title': json[i].Title,
                'Keywords': json[i].Keywords,
                'MinimumPrice': json[i].MinimumPrice,
                'MaximumPrice': json[i].MaximumPrice,
                'ResponseGroup': template.ResponseGroup,
                'sort': template.sort
            });
        }
        return qryTempArray1;
    }
    return self;
}
queryArray.prototype.qryBuilder = function() {
    var qryTempArray1 = [];
    qryTempArray1 = this.qryTempArray(this.json);
    return qryTempArray1;
}
var q = new queryArray([{
    'SearchIndex': 0,
    'Title': 'foo',
    'Keywords': 'testing',
    'MinimumPrice': 20,
    'MaximumPrice': 40
}]);
console.log(q);
console.log(q.qryBuilder());