绑定对ajax调用有什么作用? [英] What does bind do on an ajax call?

查看:88
本文介绍了绑定对ajax调用有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自ReactJS代码的示例绑定".我从未使用过bind,并且不确定在ajax调用中它会做什么,如下面的代码所示.

EXAMPLE "BIND" from ReactJS code. I have never used bind and not sure what it does on an ajax call like in the code below.

React.createClass({
    componentWillMount: function () {
        $.get(this.props.url, function (data) {
            this.setState(data);
        }.bind(this));
    },

    render: function () {
        return <CommentList data={this.state.data} />
    }
});

推荐答案

它对ajax调用没有特别的作用,它会将this值绑定到所使用的任何函数.
来自 MDN

It doesn't specifically do anything to ajax calls, it binds the this-value for any function it's used on.
From MDN

bind()方法创建一个新函数,该函数在调用时具有 this关键字设置为提供的值,并具有给定的顺序 调用新函数时所提供的参数之前的所有参数.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

一个简单的例子

function doStuff() {
    console.log(this); // would print "hello kitty"
}

var fn = doStuff.bind('Hello Kitty'); // set "this", then return new function

fn(); // call with given "this" value

问题中的简单代码将$.get函数回调内的this值设置为与componentWillMount()相同的this

The code in the question simple sets the this value inside the $.get functions callback, to the same this value as componentWillMount()

这篇关于绑定对ajax调用有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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