closures - JavaScript OOPS Question -
Here's a JavaScript Newbie I have the 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 this is going on, I hope that "HiHello" will have to be output twice in the console. Instead it outputs as expected for the first time, but NN returns for the second time.
I'm sure I'm missing something here. I thought internal functions can be used outside the Vars. Can anyone guide me? I am more of a functional UI developer and I do not have much experience with oo codes.
Thank you!
The problem is that inside echo
this
Value indicates the global object, and this.test
and this.val
(which are referring to window.test
and Window.val
) are undefined
.
You can set the value of this
resonance by applying it:
Echo. (this);
This is because you have echo ();
, then this
value is set as contained on the global object
how it works
Have a look to know.
Edit: To be able to call only echo ();
You should continue to this
value from the context of the external function, for example: There are so many ways to do this, for example:
// ... var instance = this; // External `This` value function save echo () {console.log (example.test + example.val); // use it} echo (); // ...
or
// ... var echo = (function (example) {return function () {console.log ( Examples: test + example.val);};}) (this); // External `this` value echo (); // ...
Comments
Post a Comment