1

In java it is common to call methods without explicitly declaring objects for them.

eg: new Foo().bar("foobar");

I am new to javascript, it is fair enof to call it the same way ?

  1. Is new Foo().bar("foobar"); allowed in javascript

OR

  1. Do I need to declare a variable

    var foo = new Foo(); foo.bar("foobar"); ?

1
  • 1
    1 is absolutely fine. Commented Feb 19, 2015 at 22:11

4 Answers 4

4

Yes, you can call a method without declaring a variable. Because initialization with the new operator will return a new instance of an object.

function Foo(){
   this.bar = function() {
       alert('hi');
   }
}

new Foo().bar(); // alerts hi

You can also make the method daisy-chainable.

function Foo(){
   this.bar = function() {
       alert('hi');
       return this;
   }
}

new Foo().bar().bar(); // alerts hi twice
Sign up to request clarification or add additional context in comments.

3 Comments

...but don't daisy-chain every single void method just because you can.
Simply 'Foo();' will alert hi once, the new is not needed as it is a function that returns a value that has been declared, and not a new object.
@Epiphany not in the example that I gave. Simply running "Foo()" will not return anything.
2

Your 1, new Foo().bar("foobar"); is both correct in the sense that it compiles and works as you expect, and also correct in the sense that it doesn't violate typical style conventions in JavaScript.

You can follow the rule of thumb that anything you assign to a variable can replace that variable (until that variable is updated), so:

var foo = ANYTHINGHERE
foo.bar("foobar");

can be replaced by

(ANYTHINGHERE).bar("foobar");

Comments

0
var foo = new Foo().bar('foobar') //will Work (was mistaken here originally)

var foo = null
foo = (new Foo()).bar('foobar') //will work

or as you said this will work as well.

var foo = new Foo()
foo.bar('foobar')

Comments

0

If you want an object 'Foo', with a property called 'bar' that is a function, then that is what you will want to create.

var Foo = {};  // Create the object
Foo.bar = function(){ alert('hi'); } // Create the object method

Foo.bar(); // Call the method

This method is chainable as well.

1 Comment

The method will not be chainable since the function Foo.bar doesn't return anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.