javascript - Scope for "this" keyword in nested function? -
hi have code looks this:
var myclass = { globalvar : { total : 100 }, myfunction : { gettotal : function() { return this.globalvar.total; } }, }; // uncaught typeerror: cannot read property 'total' of undefined alert(myclass.myfunction.gettotal() );
the keyword this
returns undefined, why that? because use var myclass
instead of function myclass()
?
thanks
[edit] here's jsfiddle http://jsfiddle.net/darcfiddle/cg7fk/
this
turns out myfunction
it's you're saying myfunction.globalvar.total
doesn't exist.
you could make re-usable if wanted.
function food(cost) { this.gettotal = function () { return cost + (cost * 0.05); // add 5% }; } var sandwich = new food(2.50); alert( sandwich.gettotal() ); // 2.625
http://jsfiddle.net/thetenfold/hvhxr/
there many ways make "class" (so speak).
not way, it's decent way.
Comments
Post a Comment