代码之家  ›  专栏  ›  技术社区  ›  Jamison Dance

为什么这个Javascript对象在$(document).ready之后没有超出范围?

  •  5
  • Jamison Dance  · 技术社区  · 15 年前

    为什么? 它起作用了,这从来不是一件好事。我正在努力学习更多关于面向对象javascript和javascript最佳实践的知识,所以这个组织可能看起来有点奇怪。

    CSContent 对象。我创建了一个对象的实例, content $(document).ready 并将一些事件绑定到 内容 $(文档)。准备好了吗 内容

    function CSContent() {
        var tweetTextArea = document.getElementById('cscontent-tweet'),
            tweetTextElement = document.getElementById('edit-cscontent-cs-content-tweet'),
            charCountElement = document.getElementById('cscontent-tweet-charactercount');
    
        this.toggleTweetTextarea = function () {
          $(tweetTextArea).slideToggle();
        };
    
        this.updateTweetCharacterCount = function () {
            var numOfCharsLeft = 140 - tweetTextElement.value.length;
            if (numOfCharsLeft < 0) {
                $(charCountElement).addClass('cscontent-negative-chars-left');
            }
            else {
                $(charCountElement).removeClass('cscontent-negative-chars-left');
            }
            charCountElement.innerHTML = '' + numOfCharsLeft + ' characters left.';
        };
    }
    
    
    
    $(document).ready(function () {
        var content = new CSContent();
        //If the twitter box starts out unchecked, then hide the text area
        if ($('#edit-cscontent-cs-content-twitter:checked').val() === undefined) {
            $('#cscontent-tweet').hide();
        }
    
        $('#edit-cscontent-cs-content-twitter').change(content.toggleTweetTextarea);
        //Seems wasteful, but we bind to keyup and keypress to fix some weird miscounting behavior when deleting characters.
        $('#edit-cscontent-cs-content-tweet').keypress(content.updateTweetCharacterCount);
        $('#edit-cscontent-cs-content-tweet').keyup(content.updateTweetCharacterCount);
        content.updateTweetCharacterCount();
    });
    
    3 回复  |  直到 15 年前
        1
  •  2
  •   Felix Kling    15 年前

    我想你可能想知道为什么事件处理程序

    $('#edit-cscontent-cs-content-twitter').change(content.toggleTweetTextarea);
    

    工作?

    你不能通过 content 作为事件处理程序,但包含在 content.toggleTweetTextarea . 而这个参照物在之后仍然存在 内容

    现在你可能会问为什么这些功能仍然可以访问。 tweetTextArea ? 这确实是一个终结。当函数通过 new CSContent() CSContent.toggleTweetTextarea CSContent.updateTweetCharacterCount 内容 这个函数的作用域仍然包含在其他函数的作用域链中。

    内容 以后再也没有了 ready() 完成后,这确实超出了范围。

        2
  •  5
  •   Marcel Korpel    15 年前

    这叫做闭包:局部变量 content 之后会留在记忆中 $(document).ready

    简而言之,将此函数绑定到DOM元素的事件侦听器,JavaScript垃圾收集器就会知道它应该保持局部变量不变。除非触发了事件,否则不能直接调用它(在函数外部)。对于某些函数,如果以后真的想调用函数(例如,使用 element.click() 模拟单击)。

        3
  •  1
  •   epascarello    15 年前

    $('#edit-cscontent-cs-content-twitter').change( 
        function(){ 
            content.toggleTweetTextarea(); 
        } 
    );