Mateusz Mazurek
Mateusz Mazurek

Reputation: 101

Function in object and access to 'this' property - failed

Look at this sample code:

var functions = {
 testFunction: function(){
  console.log('testFunction()', this, this.someProperty);
 }      
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();

Why this.someProperty in 2nd line is undefined?

Upvotes: 2

Views: 51

Answers (4)

Fabrício Matté
Fabrício Matté

Reputation: 70139

obj.method() is syntactic sugar for obj.method.call(obj).

Hence when you do functions.testFunction() the this reference inside of this function call points to functions.

To access it this way you would do:

var functions = {
 testFunction: function(){
  console.log(this.testFunction.someProperty); //"someValue"
 }
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();

The this keyword is well explained in this article.

Upvotes: 1

Ilya
Ilya

Reputation: 29673

var functions = {
 testFunction: function(){
  console.log('testFunction()', functions, functions.someProperty);
 }      
};
functions.someProperty = 'someValue'; // <------ you should set value to functions's property
functions.testFunction();

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

Try like this:-

var functions = {
 testFunction: function(){
  console.log('testFunction()', functions, functions.someProperty);
 }      
};
functions.someProperty = 'someValue';
functions.testFunction();

Upvotes: 1

zerkms
zerkms

Reputation: 254886

Because as you could see by a second argument console.log outputs - this refers to the functions object, not to the testFunction anonymous function.

This assignment would do what you want:

functions.someProperty = 'someValue';

Upvotes: 2

Related Questions