HACK21
HACK21

Reputation: 13

Return an object from an object method in javascript

A = {
    f1: function() {
        return {
            a: function(){ alert('sss'); }
        }
    }
}

A.f1().a();

Why is it used in this way?

Why is the method a() bound to A.f1()?

Upvotes: 0

Views: 81

Answers (2)

Hasith
Hasith

Reputation: 1767

When you do as below:

var x = A.f1();

What you get on to x is the object returned by the f1 function. which is:

{
   a: function(){ alert('sss'); }
}

now the object 'x' has function a() on it. You can call that function as:

x.a();

Which is exatly similar to:

A.f1().a();

Upvotes: 0

David G
David G

Reputation: 96865

Member function f1 of A returns an object literal with its member a set to a function. It could've also been written as:

A = {
   f1: {
        a: function() { alert('sss'); }
    }
}

A.f1.a();

Returning an object could in this case be personal preference. There is no functional difference between these two examples.

Upvotes: 1

Related Questions