Javascript的this用法及jQuery中$this和$(this)的區別

this是Javascript語言的一個關鍵字。

它表明函數運行時,自動生成的一個內部對象,只能在函數內部使用。好比,javascript

function test(){
    this.x = 1;
  }

1.this就是全局對象css

2.做爲某個對象的方法調用,這時this就指這個上級對象html

3.做爲構造函數調用,就是經過這個函數生成一個新對象(object)。這時,this就指這個新對象java

4.apply()是函數對象的一個方法,它的做用是改變函數的調用對象,它的第一個參數就表示改變後的調用這個函數的對象。jquery

 

// this實際上是一個Html 元素。 // $this 只是個變量名,加$是爲說明其是個jquery對象。 // 而$(this)是個轉換,將this表示的dom對象轉爲jquery對象,這樣就可使用jquery提供的方法操做。
(function($){ $.fn.hilight = function(options){ debug(this); var defaults = { foreground: 'red', background: 'yellow' }; var opts = $.extend({}, $.fn.hilight.defaults, options); return this.each(function() { // this實際上是一個Html 元素。 // $this 只是個變量名,加$是爲說明其是個jquery對象。 // 而$(this)是個轉換,將this表示的dom對象轉爲jquery對象,這樣就可使用jquery提供的方法操做。
            $this = $(this); // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts; // update element styles
            $this.css({ backgroundColor: o.background, color: o.foreground }); var markup = $this.html(); // call our format function 
            markup = $.fn.hilight.format(markup); $this.html(markup); }); }; // define our format function
    $.fn.hilight.format = function(txt) { return '<strong>' + txt + '</strong>'; }; // 插件的defaults
    $.fn.hilight.defaults = { foreground: 'red', background: 'yellow' }; function debug($obj) { if (window.console && window.console.log){ window.console.log('hilight selection count: ' + $obj.size()); } }; })(jQuery)

 

博客原文:app

http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.htmldom

相關文章
相關標籤/搜索