0

我的类有一个问题,我设置了一个回调函数以在 ajax 请求后触发,这工作正常,除了回调然后有 this= window 而不是 this = 调用类。我试过摆弄绑定等无济于事。任何帮助表示赞赏。

<?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();

4

2 回答 2

1

this绝不是函数的继承作用域(即闭包)的一部分,而是确定函数何时被调用,在本例中由onS(object). 以这种方式调用,函数就是 - 一个函数。您需要调用this.onS(object),但这不适用于您的情况,因为该onSuccess函数也不知道this

要使用最外层对象调用 foo/onS 函数,this您必须将对它的引用保存在另一个变量中,通常称为that

reqJSON: function(data,onS){
    var that = this;
    ...

    onSuccess: function (object){
        console.log('json success');
        that.onS(object);
    }
于 2012-06-29T11:17:24.763 回答
-1

改变这个

bar: function(){
    this.reqJSON({id:1,req:'grabpoints'},this.foo);
}

至 :

bar: function(){
  var self = this;
  this.reqJSON({id:1,req:'grabpoints'},self.foo);
}
于 2012-06-29T11:06:33.627 回答