I have the code snippet below:
var ret_ = function(x){
return x;
}
var make_cps=function(x,c_){
return c_(x);
}
var pred = {
_position: 0,
setPosition: function (i) {
_position = i
},
getPosition: function () {
return _position
},
_size: 0,
setSize: function (i) {
_size = i
},
getSize: function () {
return _size
},
_context: null,
setContext: function (x) {
_context = x
},
run: function () {
return function (c_) {
return make_cps(_position, c_);
}(ret_) == 2;
}
}
When I run it like below, it runs correctly:
pred.setPosition(2)
pred.setSize(10)
pred.setContext(null)
var res = pred.run()
console.log(res) // Output: true
but if I replace the _position to getPosition() an error occurs as getPosition() is not defined. Also if I change to this.getPosition() it says this doesn’t have a member called getPosition()
var pred = {
_position: 0,
setPosition: function (i) {
_position = i
},
getPosition: function () {
return _position
},
_size: 0,
setSize: function (i) {
_size = i
},
getSize: function () {
return _size
},
_context: null,
setContext: function (x) {
_context = x
},
run: function () {
return function (c_) {
return make_cps(this.getPosition(), c_); // gives Error here
}(ret_) == 2;
}
}
Please someone throw light on this issue.
You’ve lost your context. Where you’ve put this.getPosition(), this will return as the window object.
If you alter the line to read
It will work successfully.
Alternately, you can change the run function to read
Edit: Clarification
The reason that _position is still working rather than suffering from the same issue is that you’re not actually setting prev._position at all in your current code.
What it’s actually doing there is creating a new global variable called _position and using that instead.
This code should actually read: