2012-03-02 130 views
3

我試圖創建一個jQuery插件,以下一些官方jQuery的 - 插件方法調用

(function($){ 

    var methods = { 
    init : function(options) { 
     this.options = options; 
    } 
    , add_that: function (elem) { 
     this.append(elem); 
     return (this); 
    } 
    , add_this: function (elem) { 
     return (methods.add_that(elem)); 
    } 
    }; 

    $.fn.test = function (method) { 
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.test'); 
    }  
    }; 

})(jQuery); 

我想的方法add_that能夠附加的東西匹配的元素(一個或多個)。
現在這種方法從add_this調用。

$('#test').test('add_this', $('<div />')); 

TypeError: this.append is not a function

爲什麼我不能訪問從add_that插件(this)?

回答

6

因爲範圍從add_this調用時發生了變化。請注意,原始呼叫使用Function.apply將呼叫範圍限定爲this

if (methods[method]) { 
    return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
} 

所以,你大概可以得到解決的問題,通過使用你的方法再次申請:

add_this: function (elem) { 
    return methods.add_that.apply(this,[elem]); 
} 

活生生的例子:http://jsfiddle.net/XaUHV/

+1

謝謝你,幫我做我的[首頁]( https://github.com/Glideh/jquery.particles.burst)githubbed jquery插件:) – 2012-04-04 08:41:00

2

在你使用它的背景下「本」指的是methods.add_that

由於methods.add_that是一個函數有上沒有方法默認情況下稱爲「追加」。