Reputation: 137
I have these two objects: A and B. I want to call A.something from B, but is not working...
A = function()
{
function something()
{
//do something
}
}
B = function()
{
A.something();
}
this throws "typeError, A.something(); is not a function"...
Upvotes: 0
Views: 54
Reputation: 67296
Your current code attempts to use A
as an object when it is a function. You would need to invoke the function A()
, but then its something
method would still not be available (because it is not exposed).
If you want A
to be an object, you could use an object literal like this:
A = {
something: function()
{
//do something
}
}
B = function()
{
A.something();
}
Or for a more classical looking approach you could use new
:
function A()
{
this.something()
{
//do something
}
}
B = function()
{
var a = new A();
a.something();
}
There are more ways as well. You can use Object.create
or use a more functional approach by returning an object inside the A
function.
Upvotes: 1
Reputation: 4173
First of all, to create an object in javascript you have to define your class A
like this (easy approach, not using prototyping):
A = function()
{
return {
something = function()
{
//do something
}
}
}
Then create your object by calling var object = A()
.
So your code should look like this in the end:
A = function()
{
return {
something = function()
{
//do something
}
}
}
B = function()
{
var aObject = A();
aObject.something();
}
Upvotes: 0
Reputation: 128771
Don't declare A
as a function itself, declare it as an object:
A = {}
Then inside place something
as your function:
A = {
something: function() {
//do something
}
}
You will now be able to call A.something()
.
Upvotes: 0