function Base(x) {
this.x = x;
this.sub = new (function Sub() {
this.method = function() {
return function() {**this.super.x**}; // return an anonymous function that uses the outer x, but for reasons the anonymous function can't take parameters
}
});
}
var base = new Base(5);
console.log(base.sub.method()())
basically, in this example I'm trying to create an object Base who has a sub object sub, which has a 'method' that uses an anonymous function. The anonymous function needs the x
but cannot take in any parameters..
Is there any way to access the this.x
of Base?
At the beginning I tried the following. This works well when Base is not inherited by other objects. But in the following
"use strict";
function Base(x) {
var that = this;
this.sub = new (function Sub() {
this.method = function() {
return function() {
console.log(that); // displays Base *note[1]
return that.x;
}; // return an anonymous function that uses the outer x, but for reasons the anonymous function can't take parameters
}
});
}
function Other() {
Base.call(this); // why do I need to call Base.call(this) ?
this.setX = function(x) {this.x = x;}
}
Other.prototype = new Base();
var other = new Other();
other.setX(5);
console.log(other.sub.method()()); // otherwise undefined?
Base
is extended by Other
, after struggles I figured out I need to call Base.call(this);
in order to make it works. Otherwise console.log(other.sub.method()());
will be undefined.
If I put a console.log(that)
at *note[1]
, it will actually says the that
is a Base
object even though I construct it using var other = new Other();
I guess the problem would be solved if that
is an Other
object? What am I misunderstanding here?
My question is why do I need to call Base.call(this)
? Why does it works after calling it? Is there any better solution to this situation?