I use this setup to add properties to an object:
var obj = {
extend: function(key, obj){
this[key] = obj;
}
}
This works well. However, in some cases i want to add sub-objects as properties:
obj.extend('new', {
test: function(){
console.log('test called');
}
});
I would like to automatically wrap all functions occurring in the object passed (as second parameter) to obj.extend()
in a function which in itself wraps the actual call of the function in $(document).ready(function(){})
My approach was this:
extend: function(key, obj){
for(var prop in obj){
if(typeof prop == 'function') {
console.log(prop + ' is a function'
} else
console.log(prop + ' is NOT a function');
}
}
this[key] = obj;
}
But typeof prop
seems to return string
and not 'function'. I have checked a variety of articles and posts but the approach:
typeof propertyOfObject == 'function'
seems totally valid.
What am i doing wrong here? Why does typeof propertyOfObject
give me 'string'? How can i check if prop
is a function?
Because you're just iterating over the Object keys
, not its properties.
You need to fully qualify the property to access it:
if( typeof obj[ prop ] === 'function' ) { }