Okay, I know there are some thousand odd threads about the scope of this
in Javascript (which makes one wonder if the language was well designed) - but I still can't explain 'this' one:
//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = meow }
}
var MyCat = new Cat()
MyCat.meow()
//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = function() { alert(this.theCatName + " meow") }
}
var MyCat = new Cat()
MyCat.meow()
//works
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
Cat.prototype.meow = function() { alert(this.theCatName + " meow") }
}
var MyCat = new Cat()
MyCat.meow()
//doesn't work
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
this.meow = function() { meow() } }
}
var MyCat = new Cat()
MyCat.meow()
//doesn't work
function Cat() {
this.theCatName = "Mistigri";
function meow() {alert(this.theCatName + " meow") };
Cat.prototype.meow = function() { meow() } }
}
var MyCat = new Cat()
MyCat.meow()
Now my understanding is that in the later two cases the Cat.prototype.meow
or this.meow
are anonymous functions that happen to call meow(), which is an internal function of Cat()
- but the context of this
clearly refers to cat inside the function - What happens to it?
Here is a semi-canonical answer: See How to access the correct this / context inside a callback? But it only has the following to say about what the context of 'this' actually is:
this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables.