0
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()?

3
  • 3
    I really don't understand what the question is... Is something not working the way you expect it to? Commented Sep 5, 2012 at 2:21
  • I used to think 'A.f1().a()' shouldn't work,because method a() is not belong to f1(). Commented Sep 5, 2012 at 2:29
  • 1
    a does not belong to the function f1, it belongs to the value returned by invoking f1. Commented Sep 5, 2012 at 2:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

His is a sort of Factory method, while yours is Singleton type ?
0

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.