function Foo(x) {
this.bar = function() { return x; /* but not always */ }
}
Foo.prototype.baz = function() {
return this.bar(); // Case 2 - should return x
};
var f = new Foo(3);
f.bar(); // Case 1 - should return undefined
f.baz(); // should return x which is 3 in this case
So, bar
is an instance method of f
which is an instance of Foo
.
On the other hand, baz
is a prototype method of Foo
.
What I would like is this:
bar
should return x
(the argument passed into the constructor function), but only if it is called from within a prototype method (a method of Foo.prototype
). So, bar
should check whether the current execution context is a Foo.prototype
function, and only then bar
should return x
.
In Case 1, the current execution context is Global code, so the return value of the bar
call should be undefined
. (By this, I mean: I want it to return undefined in this case.)
However in this case 2, the current execution context is Function code of a Foo.prototype
function, so the return value of the bar
call should be x
.
Can this be done?
Update: A real-world example:
function Foo(x) {
this.getX = function() { return x; /* but not always */ }
}
Foo.prototype.sqr = function() {
var x = this.getX(); // should return 3 (Case 2)
return x * x;
};
var f = new Foo(3);
f.getX(); // should return undefined (Case 1)
f.sqr(); // should return 9
Case 1: getX
is called "directly" -> return undefined
Case 2: getX
is called from within a prototype method -> return x