[英]Javascript OOP private functions
I would like to create a constructor which can be instantiated with a json file which then is used by some private functions which in the end pass their results to a public function of the prototype. 我想创建一个可以用json文件实例化的构造函数,然后将其用于某些私有函数,这些私有函数最终将其结果传递给原型的公共函数。 Is this the right approach?
这是正确的方法吗?
Here more specific code: 这里更具体的代码:
//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
}
If I call the qryBuilder function on an Object, I get an error in the function qryTempArray at the json.length in the for loop (undefined). 如果在对象上调用qryBuilder函数,则会在for循环(未定义)中的json.length处的qryTempArray函数中出现错误。 Why that?
为什么?
As the code is written above, I'm surprised you even get to the loop. 正如上面编写的代码一样,我很惊讶您甚至进入循环。 It would seem you'd get undefined when you called qryBuilder();
调用qryBuilder()时似乎会变得不确定。 I would expect something along the lines of the following to work.
我希望以下工作能够奏效。
//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.