12.21.06

What is ‘this’ anyway?

Posted in Coding at 9:36 pm by David Kellogg

A whole book could be written about the complications of Javascript’s ‘this’. For Javascript coders who are accustomed to C++, Java or even PHP, ‘this’ becomes a mind bending subject quickly. Here’s an example that makes sense.

var global_var = 25;
function Funky(input) {
this.inside = input;
document.writeln(”this.inside: “+this.inside);
function Insider(information, parent) {
this.info = information;
document.writeln(”Inside Insider: info is “+this.info);
document.writeln(”Funky inside is “+this.inside);
document.writeln(”Parent (Funky) inside is “+parent.inside);
}
var inside = new Insider(”Too many secrets”, this);
document.writeln(”info is “+this.info);
document.writeln(”global_var: “+global_var);
document.writeln(”window.global_var: “+window.global_var);
}
var funk = new Funky(”hello funky!”);

Result:

  this.inside: hello funky!
Inside Insider: info is Too many secrets
Funky inside is undefined
Parent (Funky) inside is hello funky!
info is undefined
global_var: 25
window.global_var: 25

– DK

Leave a Comment