2
I’m having a problem checking if a certain function exists.
Code - Similar.
if(jQuery){
(function(jQuery){
jQuery.extend(jQuery.fn, {
exemplo: function(o){
var chartError = false;
function parseNumber(value){
return parseFloat(value) || 0;
}
function parseString(value){
return ''+value+'';
}
function parseBoolean(value){
return (/false/i).test(value) ? false : !!value;
}
function ucfirst(str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
// Defaults
var types = [
'string',
'number',
'boolean',
'date',
'datetime',
'timeofday',
];
if( o.type == undefined ) o.type = 'string';
if( o.value == undefined ) o.value = '';
if(!inArray(c.type, types)){
chartError = 'the content of "type" is not valid';
}
if(!chartError){
var fn = 'parse'+ucfirst(c.type);
if(typeof window[fn] == 'function'){
o.value = window[fn](o.value);
}
}
}
});
})(jQuery);
}
Situation
I’m assembling the function from a string var fn = 'parse'+ucfirst(c.type);
and I want to first validate whether the function exists if it succeeds to call it to change the data type of o.value
.
Research
how to execute a Function when i have its name
The answer is very clear, as you can see I’m even making use of it,
if(typeof window[fn] == 'function')
, however there is a problem, these functions
are not within the scope of window
, are encapsulated together with the extension of jQuery, meaning their scope is the function that I am mounting.
Question
How to check if the function exists within the scope of the extension?
Two better alternatives:
typeof f[fn] == 'function'
orfn in f
. Both returntrue
if the function exists in the object (but the second does not check whether what has there is even a function).– bfavaretto
Thank you for the day, I applied it.
– Guilherme Lautert