Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' in function inside prototype function [duplicate]

Tags:

javascript

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?

like image 312
pimvdb Avatar asked Jan 15 '11 17:01

pimvdb


People also ask

What is function __ proto __?

__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.

What are prototypes in C?

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.

What is the prototype of a function in JavaScript?

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.


1 Answers

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.

like image 146
Pointy Avatar answered Sep 23 '22 01:09

Pointy