我有下面的代码片断:JavaScript变量访问错误
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;
}
}
当运行它象下面,它运行正确:
pred.setPosition(2)
pred.setSize(10)
pred.setContext(null)
var res = pred.run()
console.log(res) // Output: true
但如果我更换_position
到getPosition()
发生错误因为getPosition()
未定义。另外,如果我改变this.getPosition()
它说this
没有一个成员叫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;
}
}
请人扔光这个问题。
难道是因为这是一个'c_',这不是在这种情况下定义的? – YePhIcK 2012-07-25 12:04:34
@YePhIcK c_被定义,它由函数的ret_参数提供。我也会添加ret_和make_cps。 – weima 2012-07-25 12:06:30