2012-03-02 129 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是一个函数有上没有方法默认情况下称为“追加”。