Why this and not $(this) in jQuery plugins

后端 未结 2 1633
陌清茗
陌清茗 2021-01-13 18:45

The docs tell us:

Let\'s say we want to create a plugin that makes text within a set of retrieved elements green. All we have to do is add a functio

2条回答
  •  一个人的身影
    2021-01-13 19:22

    Don't we use $(el).css() to normally set CSS in jQuery?

    Yes, when in the context of an element.

    However in

    $.fn.greenify = function() {
        // 'this' is a jQuery object at this point - with all the jQuery functions
        this.css( "color", "green" );
    };
    

    greenify is part of the same object that has the css function.

    Somewhere else, there is a

    $.fn.css = function() {
           ...
        };
    

    Both css and greenify are part of the prototype($.fn)

    See jQuery: What's the difference between '$(this)' and 'this'? and https://remysharp.com/2007/04/12/jquerys-this-demystified

提交回复
热议问题