[英]Javascript callback within class loses binding
I have a problem with my class where I set a callback function to fire after an ajax request, this works fine except for the callback then having this= window instead of this = the calling class. 我的类遇到问题,我将回调函数设置为在ajax请求后触发,除了回调然后具有this =窗口而不是this =调用类之外,此方法工作正常。 I have tried fiddling with the bindings etc to no avail. 我尝试摆弄绑定等都无济于事。 any help appreciated. 任何帮助表示赞赏。
<?php
if (isset($_POST['id'])){
echo json_encode(array('key' => 'val'));
die;
}
?>
<script type="text/javascript" src="/linkup/js/mootools-core-1.4.3-full-compat-yc.js" charset="utf-8"></script>
<script type="text/javascript" src="/linkup/js/mootools-more-1.4.0.1.js" charset="utf-8"></script><script>
var myClass = new Class({
blah: function(){
console.log('this worked ok');
},
foo: function(){
this.blah(); // at this point it is failing with "unknown function"
},
bar: function(){
this.reqJSON({id:1,req:'grabpoints'},this.foo);
},
// data - an aray containing some data to post {id:1,req:'grabpoints'}
// onS - a function to fire on return of data
reqJSON: function(data,onS){
if (this.jsonRequest) this.jsonRequest.cancel();
this.jsonRequest = new Request.JSON({
url: 'test.php',
onRequest: function (object){
console.log('sending json');
},
onSuccess: function (object){
console.log('json success');
onS(object);
}
}
).post(data);
},
});
var o = new myClass();
o.bar();
this
is never part of an inherited scope (ie the closure) for a function, but instead determined when the function is called, in this case by onS(object)
. this
绝不是函数的继承范围(即闭包)的一部分,而是由函数onS(object)
在调用函数时确定的。 Called this way, the function is just that - a function. 以这种方式调用的功能就是那个功能。 You need to call this.onS(object)
, but this won't work in your case because the onSuccess
function does not know about this
either. 您需要调用this.onS(object)
,但这在您的情况下不起作用,因为onSuccess
函数也不知道this
。
To call the foo/onS function with the outermost object as this
you must save a reference to it in another variable, commonly called that
: 要拨打与最外层的对象作为富/ ONS功能this
必须参考保存到它在另一个变量,通常被称为that
:
reqJSON: function(data,onS){
var that = this;
...
onSuccess: function (object){
console.log('json success');
that.onS(object);
}
change this 改变这个
bar: function(){
this.reqJSON({id:1,req:'grabpoints'},this.foo);
}
to : 至 :
bar: function(){
var self = this;
this.reqJSON({id:1,req:'grabpoints'},self.foo);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.