A JavaScript newbie here. I have this following code:
function testObject(elem) {
this.test = "hi";
this.val = elem;
console.log(this.test+this.val);
echo();
function echo () {
console.log(this.test+this.val);
}
}
var obj = new testObject("hello");
When it is run, I expect “hihello” to be outputted twice in the console. Instead it outputs as expected the first time but returns NaN the second time.
I’m sure I’m missing something here. I thought that the internal function can access the vars held outside. Can someone please guide me? I’m more of a functional UI developer and don’t have much experience with OO code.
Thanks!
The problem is that inside
echothethisvalue points to the global object, andthis.testandthis.val(which are referring towindow.testandwindow.val) areundefined.You can set the
thisvalue of echo by invoking it like:That happens because you were invoking the function by
echo();, then thethisvalue is implicitly set to the global object.Give a look to this question to learn how the
thisvalue works.Edit: For being able to calling just
echo();you should persist thethisvalue from the outer function context, there are a lot of ways to do it, for example:Or