💻

JSOM の executeQueryAsync で使われている Function.createDelegate について

2022/01/01に公開

JSOM のサンプルを見ると当たり前のように使われている Function.createDelegate について。

引数に this を渡しているのでだいたい想像がつきますが、JavaScript の this の面倒なところを解決してくれるんですね。

<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <script type="text/javascript">
        var obj = {
            web: null,
            retrieveTitle: function () {
                var ctx = SP.ClientContext.get_current();
                this.web = ctx.get_web();
                ctx.load(this.web);
                ctx.executeQueryAsync(this.onSuccess); // NG
                ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess)); // OK
            },
            onSuccess: function () {
                alert(this.web.get_title());
            }
        };
        SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
            obj.retrieveTitle();
        });
    </script>
</asp:Content>

ちなみに Function.createDelegateMicrosoftAjax.js に定義されています。

https://docs.microsoft.com/ja-jp/previous-versions/office/developer/sharepoint-2010/ee539350(v=office.14)?WT.mc_id=M365-MVP-5002941

https://docs.microsoft.com/ja-jp/previous-versions/dd393582(v=vs.100)?WT.mc_id=M365-MVP-5002941

Discussion