JavaScript accessing methods of a class

class Test {
      
      foo(f) {
         console.log(f);
      }
      
      bar(b) {
         console.log(b);
      }
      
   }
   
   var fb = new Test().foo("snafu");
   
   fb.foo();

The above code produces the following error:
TypeError: Cannot read property 'foo' of undefined at Object.< anonymous >

It has something to do with me adding on .foo("snafu") to the end of the instantiation. If I just create a new object like normal using var fb = new Test() then everything is fine and I can access the methods as usual.

I'm no java expert, but it looks like you are assigning fb to be the result of .foo("snafu"), which is probably null or void.
Hence, the failure to call its function.

So basically I'm not creating an object, fb = new Test().foo("snafu") is basically a one-time (one use only) way to access something of class Test?

Yeah.
The new Test() creates a new instance of the class, calls the function with the supplied parameter, assigns the result of that to the variable fb and then disposes of that temporary class (or puts it in the garbage pile for later disposal).

The easiest option is to just do:
var fb = new Test();
fb.foo("snafu");

etc. It is more lines of code, but it's clearer what you want the code to do.
Also, in saying it is more lines of code, the compiler would have had to do the intermediate step of creating and referencing the class anyway. So it wont run any slower.

1 Like

This is JavaScript, not Java.

But you're right. He's assigning the Result of that function to the variable, which at least in the case of this pseudo-code is doesn't even return anything.

Of course it works when you're doing fb = new Test() because then you are actually storing that object reference in the variable, not just the result of the function called.

Also if you want to access a property of the created object, why f()? It should just be f and then the property needs to be an actual property in the Object, not just a "anonymous" variable inside the function called.

?
Not sure what you mean.

There is neither an f property, nor an f function in that code, or am I missing something?

Sorry, typo. I've corrected the initial post. It should be fb.foo() not fb.f()

Exactly what I meant :smiley:

I was just experimenting, instead of using an anonymous function or constructor to kickoff a process. So there is no scenario where var fb = new Test().foo("snafu") makes sense? I understand in the current format it doesn't work, but maybe if something was tweaked it would work?

Well, unless you actually wanted the return of that function in your variable, and you don't need the object instance later, I couldn't think of anything right now.