user656925
user656925

Reputation:

Calling methods from a Javascript Object

If I have

var function_holder = { 

        someFunction: function () { } 
}; 

How do I call someFunction.

Also is there a way to write someFunction outside of function_holder?

Thanks

Upvotes: 1

Views: 100

Answers (5)

Austin
Austin

Reputation: 596

There are a couple different ways to do what you want to do.

function function_holder() {

    this.my_function = function() {};
};

You would call this by instantiating function holder as such.

var fc = new function_holder();
fc.my_function();

Or alternatively you could do it this way.

function function_holder() {};

function_holder.prototype.my_function = function() {};

You would call this the following way:

function_holder.my_function();

Upvotes: 0

Raynos
Raynos

Reputation: 169391

function_holder is an object, someFunction is a method.

Call function_holder.someFunction(); to invoke the method.

You can define the function seperately as either a function declaration

function someFunction() {
    // code
} 

or a function variable

var someFunction = function () {
    // code
}

Upvotes: 2

Brandon
Brandon

Reputation: 456

call it:
function_holder.someFunction() This will execute the function like the others say.

I think I have an idea what you mean by "write someFunction outside of function_holder?"..

var theFunc = function(){};
function_holder = {};
function_holder.someFunction = theFunc;

There are lots of ways to do anything in javascript.

Upvotes: 0

Lenar Hoyt
Lenar Hoyt

Reputation: 6159

You could write this instead:

function_holder.someFunction = function() { }

You can call the function this way:

function_holder.someFunction()

Upvotes: 0

Joe
Joe

Reputation: 82604

Call it:

function_holder.someFunction()

From outside:

function other() {
    alert('Outside');
}

var obj = {
    someFunction: other
};

obj.someFunction(); // alerts Outside;

Upvotes: 0

Related Questions