I’m trying to learn JS from online tutorial – http://ejohn.org/apps/learn/#33 , you can test JS code there. I’m trying to understand nesting functions as methods inside of other functions and what “this” keyword is referencing then. Why if I put on above site code from below – it doesn’t work? Could someone explain that aspect of JS?
function Ninja(name){
this.name = name;
this.changeName = function(newname) {
this.name = newname;
this.anotherFunction = function(newname2) {
this.name2 = newname2;
}
}
}
var ninja = new Ninja("John");
assert( ninja.name == "John", "The name has been set on initialization" );
// ninja.anotherFunction("Luken");
// ninja.changeName.anotherFunction("Luken");
// Why both above functions doesn't work?
assert(ninja.name2, "It works?");
ninja.changeName("Bob");
assert( ninja.name == "Bob", "The name was successfully changed." );
It’s fairly simple:
What happened: simple, by invoking the changeName method,
anotherFunctionwas defined and assigned tothis. At that timethisreferenced theNinjaobject, so the method was assigned to the instance ofNinjafrom which thechangeNamemethod was invoked. Prior to calling thechangeNamemethod, theanotherFunctionmethod simply didn’t exist.Though this might seem useless or stupid, it does make sense. What you need to remember is that functions/methods are, in essence stand-alone objects. In this code, they just happen to be defined as properties/methods, but they needn’t be used as such. Going back to the code above:
The
changeNamemethod can be applied to any object, adding a new method, changeing/adding certain properties to that particular instance.