im struggling with a script where a method/object returns undefined
var Lang = new function(){
this.get = function(str, trans){
if(TRANSLATE[str]){
var str = TRANSLATE[str][LANG];
if(count_obj(trans) > 0){
for(var key in trans){
str = str.replace('%'+key+'%', trans[key]);
}
}
return str;
}
};
};
function Language(){
this.tbl_list = null;
this.append = function(string, obj, index){
var row = $('<tr></tr>')
.append('<td class="list_row">'+js2txt(string)+'</td>');
for(var key in obj){
row.append('<td class="list_row">'+js2txt(obj[key])+'</td>');
}
var td = $('<td class="list_row"></td>').appendTo(row);
//var inp_edit = $('<input type="button" value="'+Lang.get('BTN_EDIT')+'" />');
alert(Lang.get);
List.append_row(row, this.tbl_list, index);
开发者_运维百科 };
};
alert(Lang.get);
inside the Language object Lang.get
returns undefined, but outside it returns the function!?
I think this is where you went wrong:
var Lang = new function(){
Don't use new
when assigning a function to a variable. Do this:
var Lang = function(){
> var Lang = new function(){
> this.get = function(str, trans){
> if(TRANSLATE[str]){
> var str = TRANSLATE[str][LANG];
> if(count_obj(trans) > 0){
> for(var key in trans){
> str = str.replace('%'+key+'%', trans[key]);
> }
> }
> return str;
> }
> }; };
I don't see a reason for using new above, it's just a waste of resources. Since Lang doesn't seem to be called as a constructor, it should, by convention, start with a lower case letter. Why not:
var lang = {
get: function(str, trans) {
// function body
}
};
.
> function Language(){
> this.tbl_list = null;
>
> this.append = function(string, obj, index){
> /* snip */
> alert(Lang.get);
> /* snip */
> }; };
alert(Lang.get); // shows source of Lang.get
inside the Language object Lang.get returns undefined, but outside it returns the function!?
How are you calling it? It appears to be a constructor, so:
var x = new Language(); // Create instance lf Language
x.append(); // Shows Lang.get
Which is the same result as calling Language
as a function. What is the issue?
Also, the jQuery stuff seems to be very inefficient. You might want to work on that. e.g.
> var row = $('<tr></tr>')
> .append('<td class="list_row">'+js2txt(string)+'</td>');
would be much better as:
var row = $('<tr><td class="list_row">'+js2txt(string)+'</td></tr>');
Or even better would be to create a single row with the structure you want, clone it for each row, then just replace the content of the cell.
The Language
function definition and initialization are hoisted above the var Lang
initialization. Is it possible that Language
is being called before the initializer for Lang
is reached?
精彩评论