Can I Create A Function That's A Property Of A Function In An Object?
Solution 1:
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.
Solution 2:
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 (newMyObject).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.
Solution 3:
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
Solution 4:
Here is a fix to your code with minimum changes:
functionMyObject() {
functionarrayCreate(array) {
var myArray = array;
arrayCreate.arrayLength = function() {
return myArray.length;
}
}
this.create = arrayCreate;
// Do something else here...
}
var foo = newMyObject();
foo.create([1,2,3]);
console.log(foo.create.arrayLength());
Solution 5:
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...
Post a Comment for "Can I Create A Function That's A Property Of A Function In An Object?"