Reputation: 829
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
Reputation: 1294
You also could use
b = new a();
b.name = 'Jane',
b.greeting = 'Hi'
b.sayIt();
Upvotes: 0
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!
Upvotes: 0
Reputation: 191058
You can use apply
or call
.
a.sayIt.apply(b);
These change the value of this
.
Upvotes: 3