salacis
salacis

Reputation: 205

Can I create a function that's a property of a function in an object?

I would like to access a function within an object like this

    function MyObject()
    {
        this.create = function(array)
        {
             var myArray = array;
             this.arrayLength = function(){return myArray.length;}

             // Do something else here...
        }
    }
    var foo = new MyObject();
    foo.create(value);
    console.log(foo.create.arrayLength(););

I get undefined as response for .create.length(), is it even possible to do it that way?

Upvotes: 0

Views: 81

Answers (5)

Virus721
Virus721

Reputation: 8315

in :

this.create = function(array)
{
     var myArray = array;
     this.arrayLength = function(){return myArray.length;}
}

this refers to foo, because you're calling create using something.create() instead of new MyObject.create() in which case this would refer to the instance of create. Which means that arrayLength is not a property of the function create, so you can't call it this way.

var foo = new (new MyObject).create();
console.log(foo.create.arrayLength(););

Would work however.

If you told us what you want to do we would surely think of a less weird way.

Upvotes: 1

Joe Simmons
Joe Simmons

Reputation: 1848

It was explained pretty well above what the problem is.

So to fix it, just change the line where you define the arrayLength method.

Change this line: this.arrayLength = func...

To this: this.create.arrayLength = func...

Upvotes: 0

closure
closure

Reputation: 7452

Here is a fix to your code with minimum changes:

function MyObject() {

  function arrayCreate(array) {
    var myArray = array;
    arrayCreate.arrayLength = function() {
      return myArray.length;
    }
  }

  this.create = arrayCreate;
  // Do something else here...
}
var foo = new MyObject();
foo.create([1,2,3]);
console.log(foo.create.arrayLength());

Upvotes: 0

Paul S.
Paul S.

Reputation: 66334

I'm not sure what your ultimate goal is so I'll say something I haven't seen yet

var foo = new MyObject();
// `foo` has no property _arrayLength_
foo.create([1, 2, 3]); // _create_ sets `this.arrayLength`
// `foo` now has property _arrayLength_
foo.arrayLength(); // 3

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150030

When you call the .create() method with foo.create(), then within .create() this is foo. So this line:

this.arrayLength = function(){return myArray.length;}

creates a method arrayLength() on foo. So just use:

console.log(foo.arrayLength());

If for some reason you actually want arrayLength() to be a method of create you could do this:

this.create.arrayLength = function(){return myArray.length;}

and then use your original:

console.log(foo.create.arrayLength());

(minus the extra semicolon that was before the closing bracket).

But while the latter version "works" it seems kind of a strange way to go.

Upvotes: 4

Related Questions