outterscope and innerscope this

4 views
Skip to first unread message

Yan Wang

unread,
May 2, 2017, 2:52:43 PM5/2/17
to JPassion.com: JavaScript Programming
could someboy explain me why
this in outerscope is JQueryObject
but this in inner scope is DOM Object?

i did console.log(this), looks like both are javascript object,
outterscope is javascript wrapper of dom
innerscope is javascript wrapper of jqueryobject

Rgds
Yan

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>

    <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
        // Create a plugin
        (function($) {
            count = 0;
             console.dir(this);// ---> outter scope
            $.fn.sayGreeting = function() {
                // The "this" in the outer scope is jQuery object but 
                // the "this" in the inner scope is DOM object
                // so it has to be converted to jQuery object via $(this) 
                // before “prepend” method can be invoked
                this.each(function() {     /// Add iternation
                    $(this).prepend((++count) + " Hello, ");
                    console.dir(this);// ---> inner scope
                });                        
            };
        })(jQuery);

        // Use the plugin
        $(document).ready(function() {
            $('p').sayGreeting();
        });
    </script>

    <p>Big Bang</p>
    <p>Super Junior</p>

</body>
</html>
Reply all
Reply to author
Forward
0 new messages