0

I have a javascript function (using NodeJS but not particularly relevant here) like this:

var method = {};
method.create = function(){
  console.log('Method was created')
}

method.create.function1 = function(){
  console.log("This is method 2")
}

method.create.series = ['one', 'two', 'three'];

If I call method.create.function1() it correctly runs that function and console logs: This is method 2.

If I call method.create.series[0], I am returned: "one"

However, if I call:

 var app = method.create();
 app.function1() // returns undefined

I've tried:

var method = {};
method.create = function(){
    console.log('Method was created')

    this.function1 = function(){
      console.log("This is method 2")
    }

    this.series = ['one', 'two', 'three'];
}

but this doesn't work at all. Anything I can do to be able to pass these methods along to a new variable?

2
  • Why would that work? method.create() returns undefined. Commented Apr 26, 2014 at 8:00
  • 1
    FWIW, method is a very misleading thing to call a variable that refers to an object rather than a function. It's also fairly unusual to assign functions as properties on function objects, although it can certainly be useful in some cases (KnockoutJS does it with observables, for instance, and of course all normal JavaScript functions have methods on them like call, apply, ...). Commented Apr 26, 2014 at 8:04

1 Answer 1

2

There's a big difference between the expressions method.create and method.create(). The first results in a reference to the function object; the second calls the function and results in its return value. Since your create function doesn't return anything, the result of calling it is the value `undefined.

If you want to have a reference to method.create in app and then use it, you use the first expression (without ()):

var app = method.create;
app.function1(); // Works
Sign up to request clarification or add additional context in comments.

Comments

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.