JavaScript 原型函数调用
JavaScript prototype function call
这是PhoneGap应用程序,但我认为它在这里无关紧要。所以这是我正在使用的代码:
function Geolocation(){
this.maximumAge = 3000;
this.timeout = 20;
this.enableHighAccuracy = true
this.geolocation = navigator.geolocation.getCurrentPosition(this.onSucess, this.onError, {maximumAge : this.maximumAge, timeout : this.timeout, enableHighAccuracy: this.enableHighAccuracy});
}
Geolocation.prototype.onSucess = function(position){
}
Geolocation.prototype.onError = function(error){
alert( typeof this.onSucess );
}
每当触发 onError 时,此警报都会返回undefined
。为什么会这样?
因为this.onError
没有使用正确的上下文调用。您可以尝试Function.bind()
:
navigator.geolocation.getCurrentPosition(
this.onSucess.bind(this),
this.onError.bind(this),
//...
onSuccess
也是如此.
除了成功拼写错误之外,还没有办法确定。
JavaScript使用"this"的棘手之处在于,"this"不是由方法的定义决定的,而是由它的调用方式决定的。
我最近在另一个类似的问题中解释了这一点:
"这个"如何影响方法的方法?
例如,我可以定义一个指向您的函数的变量:
var blah = this.onSucess;
blah(); // "this" will be undefined
var bleh = {
test: this.onSuccess
}
bleh.test(); // "this" will be the object literal.
当getCurrentPosition调用你的回调函数时,它可能只是直接调用它:
onSuccess(position);
因此没有定义"这个"。
你可以做的是将一个包装器/代理函数传递给它,该函数具有对地理位置对象的闭包引用,以便它可以调用this.onSuccess:
function Geolocation(){
this.maximumAge = 3000;
this.timeout = 20;
this.enableHighAccuracy = true
this.geolocation = navigator.geolocation.getCurrentPosition(function (position) {
this.onSucess(position);
},
function (error) {
this.onError(error);
},
{
maximumAge : this.maximumAge,
timeout : this.timeout,
enableHighAccuracy: this.enableHighAccuracy
});
}
如 David 所示,执行此操作的一种简写方法是使用 Function.bind,它返回一个包装函数,执行我所描述的操作,如下所示:
function Geolocation(){
this.maximumAge = 3000;
this.timeout = 20;
this.enableHighAccuracy = true
this.geolocation = navigator.geolocation.getCurrentPosition(this.onSucess.bind(this),
this.onError.bind(this),
{
maximumAge : this.maximumAge,
timeout : this.timeout,
enableHighAccuracy: this.enableHighAccuracy
});
}
this.onError 正在另一个上下文中运行。 它在 navigator.geolocation 的上下文中运行。
如果要在地理位置上下文中运行this.onError,则必须使用如下所示的代理方法:
proxy = function(func, context) {
func.apply(context);
}
用法:
proxy(this.onError, this)
例如,请参阅以下内容:
http://jsfiddle.net/Z32BZ/
祝你有美好的一天:-)
相关文章:
- 使用setInterval调用原型函数时出现问题
- 从同一原型和上下文中的另一个函数调用函数
- Javascript原型继承原型函数调用
- JavaScript–从另一个原型函数调用原型的一个函数
- JavaScript 原型函数调用
- 通过引用调用原型函数时,类会丢失“this”作用域
- 调用原型函数的元素是什么
- 从继承对象的函数调用原型的方法
- 调用原型的函数
- 通过按钮点击调用原型函数不起作用
- 从原型函数调用函数
- HTML5/webcomponents:从模板代码调用原型函数
- 当原型函数调用javascript中的常规函数时会发生什么?
- 为什么通过setTimeout调用原型函数时会丢失实例信息?
- Onchange原型函数调用
- 从其他原型调用原型中的函数
- 调用原型中列出的函数
- 如何在同一对象中调用原型函数
- 从另一个调用函数的原型,通过单击 html 元素调用
- Javascript 在构造函数中调用原型函数