javascript变量的范围

时间:2011-05-24 05:32:10

标签: javascript

我是JavaScript的新手,我无法理解一些脚本中的变量范围,我已经从我找到的示例拼凑起来了。下面的代码是Matt Berseth在他的网站上发布的教程的一部分。该应用程序有一个ajaxToolKit:ModalPopupExtender,带有JavaScript函数,可在单击Yes或No按钮时执行。应该保存删除按钮位置和div的两个变量似乎没有填充,因此代码异常。当我单击Yes或No按钮时,_Source和_popup变量都是未定义的。

我真的很感谢在我的代码中解释我设置错误的时间。

The button that is fires the OnClientClick event calling the SubmitPayment function    
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return SubmitPayment(this); return false;" UseSubmitBehavior="False" AccessKey="S" ValidationGroup="Manual" />

A hidden field to save a value in (tested later in the javascript)
    <div id="divHiddenFields">
        <asp:HiddenField ID="hfTotalAmtDue" runat="server" />
    </div>

The Dialog Panel
    <div id="divConfirmPaymentDialog">
        //panel that makes up confirmation dialog
        <asp:Panel ID="pnlConfirmPaymentDialog" runat="server" style="display:none" CssClass="modalPopup" Height="200" Width="450">
            <div align="center">
                <p class="info">You are attempting to make a payment when your account(s) has/have no balance!</p>
                <p class="info">If you do this you will have a credit applied to your account in the amount of your payment.</p>
                <p class="info">Are you sure that you want to do this?</p>
                <asp:Button ID="btnConfirmPaymentYes" runat="server" Text="Yes" Width="75" />
                <asp:Button ID="btnConfirmPaymentNo" runat="server" Text="No" Width="75" />
            </div>
        </asp:Panel>
        //modal dialog extender that implements showing the modal dialog with panel
        <cc1:ModalPopupExtender ID="mpeConfirmPayment" runat="server" BehaviorID="mpeConfirmPaymentBehaviorID" BackgroundCssClass="modalBackground" 
        CancelControlID="btnConfirmPaymentNo"  OnCancelScript="btnConfirmPaymentNo_Click();" OkControlID="btnConfirmPaymentYes" OnOkScript="btnConfirmPaymentYes_Click();" 
        PopupControlID="pnlConfirmPaymentDialog" TargetControlID="pnlConfirmPaymentDialog" />
    </div>   

The Javascript
    <script type="text/javascript">       
        //this system function sets the App_init handler function as the initialization handler
        Sys.Application.add_init(App_Init);
        //this function handles the hookup of the beginrequest and endrequest ="divhandlers.  The two functions are called
        //at the begin and end of the webpage lifecycle
        function App_Init()
        {
          Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
          Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
        }
        //this function handles the begining of the webpage lifecylce
        function BeginRequest(sender, args){
            $(document).ready(function(){
                //if btnYes was clicked then block the UI
                $('#<%= btnYes.ClientID %>').live('click', function(e){
                    //e.preventDefault();
                    $.blockUI();
                });
            });
        }
        //this function handles the end of the webpage lifecylce
        function EndRequest(sender, args) {
            //call unblockUI 
            $(document).ready(function() {
                $('#<%= btnYes.ClientID %>').live('click', function(e) {
                    $.unblockUI();
                });
            });

            //check for errors that occurred during page execution
            if (args.get_error() != undefined) {
                var errorMessage;
                if (args.get_response().get_statusCode() == '200') {
                    errorMessage = args.get_error().message;
                }
                else {
                    // Error occurred somewhere other than the server page.
                    errorMessage = 'An unspecified error occurred. ';
                }
                args.set_errorHandled(true);
                if (errorMessage.indexOf('ValidationError:') > 0) {
                    alert(errorMessage.replace('Sys.WebForms.PageRequestManager', '').replace('ServerErrorException:', ''));
                }
            }
        }
        //this funcion will raise the viewccreceipt dialog when called
        function OpenReceipt() {
            window.open('ViewCCReceipt.aspx', 'Name', 'height=600,width=800');
        }

        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;

        //This function will be called when the submit button on the creditcard entry screen is pressed.
        //The function will check to see if the balance is already zero and message the customer that they will have a
        //credit balance if they continue and allow the to confirm the payment.
        function SubmitPayment(source) {
            $(document).ready(function() {
                //Get the Total Amount Due from hidden field hfTotalAmountDue
                var TotalAmtDue = $('#<%= hfTotalAmtDue.ClientID %>').val();
                if (TotalAmtDue <= 0) {
                    this._source = source;
                    this._popup = $find('mpeConfirmPaymentBehaviorID');
                    //  find the confirm ModalPopup and show it    
                    this._popup.show();
                }
            });
        }
        //event handler for the btnConfirmPaymentYes button
        //when this handler is executed the modal popup is hidden and a postback is done
        function btnConfirmPaymentYes_Click(){
            //  find the confirm ModalPopup and hide it    
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, '');
        }
        //event handler for the btnConfirmPaymentNo button
        //when this handler is executed the modal popup is hidden and the postback permanently shut down
        function btnConfirmPaymentNo_Click(){
            //  find the confirm ModalPopup and hide it 
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>

2 个答案:

答案 0 :(得分:2)

this._source与JavaScript中的var _source不同。

而不是做

this._source = source;
this._popup = $find('mpeConfirmPaymentBehaviorID');

也许你应该做

_source = source;
_popup = $find('mpeConfirmPaymentBehaviorID');

将它(在文档加载时)分配给在包含事件处理函数定义的作用域中声明的变量:btnConfirmPayment{No,Yes}_Click

很多时候两者是等价的,因为this默认引用全局范围,并且var声明在全局范围内,但在加载事件处理程序时可能运行{ {1}}是一些DOM节点。

答案 1 :(得分:1)

范围很棘手,这是基础知识。

唯一的范围是功能范围。函数中声明的变量保留在函数中。在函数外部声明的变量属于全局范围。但是要避免使用全局变量,因为它们的风格很差。

函数是没有home的对象。在两种情况下,您只能依赖this的值:

  • 您调用了这样的函数:functionname.call(context, params),其中context是this的值
  • 您的功能是另一个对象的一部分。 this将成为它的一部分
    • 注意:如果该功能与该功能分离,则所有投注均已关闭

如果以这种方式调用函数:functionname(params),那么this将是调用范围内的任何内容。这有点奇怪,所以如果你要使用它,请确保你知道它是什么。

您应该假设this永远不会引用全局范围,并且绝不应在全局范围内使用this

我会使用某种打包器来避免使用全局范围。我使用ender.js,这很好,因为默认包与jQuery非常相似,所以学习曲线很小。

Douglas Crockford是解释JavaScript的人:

http://javascript.crockford.com/