簡體   English   中英

Javascript OOP私有函數

[英]Javascript OOP private functions

我想創建一個可以用json文件實例化的構造函數,然后將其用於某些私有函數,這些私有函數最終將其結果傳遞給原型的公共函數。 這是正確的方法嗎?

這里更具體的代碼:

//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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM