RobertJoseph
RobertJoseph

Reputation: 8158

How to access a property on a function?

I am just starting to learn Javascript and was experimenting with functions. I wrote the following thinking that it would work. Is something like this possible or is it just wrong?

function foo() {
   console.log(this.language);
}

foo.language = "English";

foo();

Upvotes: 1

Views: 321

Answers (4)

sapy
sapy

Reputation: 9602

Javascript only supports prototypal Inheritance. So to assign a property (in your case language is the property) to an Object (in your case foo) you need to use constructor. And by convention constructor are written Initcap.

function Foo(lang){
 this.language = lang;
}

Foo.prototype.getLanguage = function(){
  return this.language;
}

var lang1 = new Foo('english');
var lang2 = new Foo('bengali');

console.log(lang1.getLanguage()); // english
console.log(lang2.getLanguage()); // bengali

Upvotes: 1

Trace
Trace

Reputation: 18899

It is not possible, because to gain access to this as the current object, you'll need to instantiate the (constructor) function, which is what invoking new will do for you. Accessing this for a reference to the current instance is not only the case in Javascript though; in Java, this also isn't accessible from static context.

What you're looking for is something like:

function Foo(language) {
   this.language = language; 

}
Foo.prototype.log = function(){
   console.log(this.language); 
}    
var bar = new Foo("English"); 
bar.log(); 

Upvotes: 2

whistling_marmot
whistling_marmot

Reputation: 3903

You can make a foo object (an instance of foo) using the new keyword. Then set the language property of that instance. If foo has a function to output its language property, then you can invoke that function on your instance to see its language.

function foo() {
    this.outputLanguage = function() {
        console.log(this.language);
    }
}

var f1 = new foo();
f1.language = "English";

var f2 = new foo();
f2.language = "French";

f1.outputLanguage();
f2.outputLanguage();

In this example, we make 2 foo objects, and assign each a different language.

The foo() function is a constructor function. We usually pass the initial values of the instance variables to it, like this:

function foo(language) {
    this.language = language;
    this.outputLanguage = function() {
        console.log(this.language);
    }
}

var f1 = new foo("English");
var f2 = new foo("French");

f1.outputLanguage();
f2.outputLanguage();

Upvotes: 1

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11940

this is available on instance variables, in your case it's named function

function foo() {
   console.log(foo.language); //instead of this, use function property
}

foo.language = "English";

foo();

If you want to dive more, checkout my other answer for the same topic

Upvotes: 0

Related Questions