🔧

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

に公開

JSOM のサンプルでは、Function.createDelegate がよく使用されています。今回の記事では、この Function.createDelegate について解説します。

引数に this を渡しているため、JavaScript の this の扱いに関する課題を解決できることが想像できます。Function.createDelegate を利用することで、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.createDelegate は MicrosoftAjax.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