I basically have an object, extended with a function through its prototype. Inside that function, another function exists, however when using this
in this nested function, it does not seem to refer to the object, but the function.
For example,
var sampleObject = function() { this.foo = 123; } sampleObject.prototype.getFoo = function() { var nested = function() { return this.foo; } return nested(); } var test = new sampleObject(); window.alert(test.getFoo()); // undefined
The this.foo
does not refer to the 123 value, but is undefined as this refers to the nested function, in which no foo
exists. How can I access the 123 value from the nested function?
__proto__ is a non standard accessor to the prototype, which is supported across browsers, but not by IE. Anyway is not meant to be used by application code. Follow this answer to receive notifications.
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
sampleObject.prototype.getFoo = function() { var me = this; var nested = function() { return me.foo; } return nested; }
By saving the value of this
in a local variable, you make it explicitly part of the lexical context for that function and for all nested function scopes. Thus, on the call to "nested", that inner function will have its own scope (it's own this
value), but it can still refer to the variable "me" in the enclosing scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With