Dan
Dan

Reputation: 829

How do I access a function of a different object

I have the following code -

function test() {
        a = {
            name : 'John',
            greeting : 'Hello',
            sayIt : function() {
                return this.greeting + ', ' +
                    this.name + '!';
            }
        };

        b = {
            name : 'Jane',
            greeting : 'Hi'
        };
}

How can I access sayIt using b? Ofcourse b.sayIt will not work. I need to print 'Hi Jane'. How can I pass the name and greeting of b to sayIt function?

Upvotes: 1

Views: 99

Answers (4)

stekhn
stekhn

Reputation: 2087

Use Function.prototype.apply:

a.sayIt.apply(b)

Upvotes: 0

user3154108
user3154108

Reputation: 1294

You also could use

b = new a();
b.name = 'Jane',
b.greeting = 'Hi'
b.sayIt();

Upvotes: 0

Andy
Andy

Reputation: 63587

You need to return a and b from the function. Then you can do this:

function test() {
  var a = {
    name : 'John',
    greeting : 'Hello',
    sayIt : function() {
      return this.greeting + ', ' +
      this.name + '!';
    }
  };

  var b = {
    name : 'Jane',
    greeting : 'Hi'
  };

  return this;
}

test().a.sayIt.call(test().b); // Hi Jane!

DEMO

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191058

You can use apply or call.

a.sayIt.apply(b);

These change the value of this.

Upvotes: 3

Related Questions