0

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"...

3 Answers 3

1

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.

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

Comments

0

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

Comments

0

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

3 Comments

How about the other ways to create an object? new or Object.create come to mind...
Well, that would be far to much to cover in this post. I will not write a tutorial on how to do object oriented coding in js
I was referring to the you have to part of the first sentence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.