Here is a little Javascript code snippet where I have used a function to simulate an object. I tried to reflect upon the member functions (which are really nested functions of the function) , but somehow the code does not work.
Can someone please help me understand why the code does not work. I am trying to understand the underlying principles of Javascript which cause this code to not work.
Thanks.
var test = function () {
var first = function first () {
alert ("first");
}
var second = function second () {
alert ("second");
}
};
function getOwnFunctions(obj) {
for(var f in obj) {
if(typeof(f) == "function" && obj.hasOwnProperty(f)) {
alert(f);
}
}
}
getOwnFunctions(test);
A couple points here:
vardefines the scope of the variable, which is saying that thefirst&secondfunctions areonly available inside the
testfunction. To simulate a
object,you want to use the
thiskeyword.for(var f in obj): theforloopsover the object and returns the
keys in
obj, sotypeof(f)will always return the type of thefvariable which will be astring, you want to check fortypeof(obj[f]])which will returnthe type of the actual underlying
property.
getOwnFunctionswith a instance of
test, not theactual
testfunction:.