JavaScript对象的函数原型定义中捆绑问题 [英] Javascript object binding problem inside of function prototype definitions

查看:106
本文介绍了JavaScript对象的函数原型定义中捆绑问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出绑定一个函数原型稍后调用正确的地方。这个例子充分code可以在这里找到:

I am trying to figure out the right place to bind a function prototype to be called later. The full code of the example can be found here:

http://www.iprosites.com/jso/

我的JavaScript的例子是非常基本的:

My javascript example is very basic:

function Obj(width, height){
    this.width = width;
    this.height = height;
}

Obj.prototype.test = function(){
    var xhr=init();
    xhr.open('GET', '?ajax=test', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.onreadystatechange = function() {
        if (xhr.responseText == '403') {
            window.location.reload(false);
        }
        if (xhr.readyState == 4 && xhr.status == 200) {
            this.response = parseResponse(xhr.responseText);
            document.getElementById('resp').innerHTML = this.response.return_value;
            this.doAnotherAction();
        }
    };
    xhr.send();
}

Obj.prototype.doAnotherAction = function(){
    alert('Another Action Done');
}


var myo = new Obj(4, 6);

如果您尝试运行myo.test()在Firebug,你会得到this.doAnotherAction不是一个函数的回应。 2.支持功能init()和parseResponse()可以发现,在test.js如果你想查看这些链接,但不应该是这个问题太重要。我肯定this.doAnotherAction()认为,这是从一个instanceof测试预期XMLHtt presponse对象。

If you try to run myo.test() in Firebug, you will get the "this.doAnotherAction is not a function" response. The 2 support functions init() and parseResponse() can be found in the test.js link if you wish to view them, but should not be too relevant to this problem. I've affirmed that this.doAnotherAction() thinks "this" is the XMLHttpResponse object as expected from an instanceof test.

任何人都可以对方向的一些见解与结合帮助吗?我试过一切似乎没有工作!

Can anyone help with some insight on direction with binding? Everything I've tried seems not to work!

我使用MooTools的,虽然图书馆是不是在这个例子present。

I do use Mootools, although the library is not present in this example.

由于提前,

阿里昂

推荐答案

ECMAScript的第5版。借用了从原型框架功能的绑定方法。您可以包括在你的code它将定义绑定方法,如果它不是已经present。

ECMAScript 5th ed. has borrowed the bind method on functions from the Prototype framework. You can include it in your code which will define a bind method if it's not already present.

if (!Function.prototype.bind)
{
    Function.prototype.bind = function() {
        var fn = this, 
            args = Array.prototype.slice.call(arguments), 
            object = args.shift();

        return function() {
            return fn.apply(object,
                args.concat(Array.prototype.slice.call(arguments)));
        };
    };
}

一旦定义,你可以用绑定obj的对象的onreadystatechange 回调内部的匿名函数。

xhr.onreadystatechange = function() {
    ...
}.bind(this);

这篇关于JavaScript对象的函数原型定义中捆绑问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆