I’m trying to make a function that can be applied to a value returned from another function both within a function. Since that’s probably a terrible explanation, here’s a simplified sample:
function MainFnc() {
this.subFnc=function(a) {
return a*2
}
this.subFnc.subSubFnc=function(a) {
return this*a
}
}
This isn’t my actual code – it’s for a far better reason than multiplying numbers. This is just a simplified example of what I’m trying to achieve. My question is whether or not it’s actually possible to go this deep, and if so how? The method I’ve portrayed in this sample code evidently does not work.
Thanks for any help.
Edit: Here’s an example of it in use since not everyone understands clearly what I want to do with this:
anObject=new MainFnc;
alert(anObject.subFnc(2)); //returns 4
alert(anObject.subFnc(2).subSubFnc(2); //returns 8
This is not exactly what I’m doing, it’s just easier to understand using simple multiplication.
Update based on your comment:
Right now, you’re returning a number from your
subFnc, and so the expressionMainVar.subFnc(2).subSubFnc(2)breaks down like this:subFnconMainVar; it returns a function reference.this=MainVar; this returns the number2.subSubFncon the number2; it returnsundefined.this=2; fails because you can’t callundefinedas a function.More: You must remember
thisand Mythical MethodsTo do what you’re doing, you’d have to have
subFncreturn an object with function properties. You could do it like this:…and then call it like this:
Live example
Note the
getfunction to return the underlying number. You might also add atoString:But the above isn’t taking advantage of prototypical inheritance at all (and it will be important to, if you’re creating all of those objects; we need to keep them lightweight); you might consider:
Original Answer:
With that code, if you did this:
…because
thisinsidesubSubFncwhen called like that issubFnc, and multipling a function reference tries to convert it to a number, which comes outNaN, and so the result of the multiplication isNaN.Remember that in JavaScript,
thisis defined entirely by how a function is called, not where the function is defined. When you call a function via dotted notation (a.b();), the object you’re looking up the property on becomesthiswithin the function call, and so witha.b.c();,thiswithinc()isb, nota. More: You must rememberthisand Mythical Methods