Javascript 定义自定义jQuery对象属性的最佳方法?
我希望Javascript 定义自定义jQuery对象属性的最佳方法?,javascript,jquery,Javascript,Jquery,我希望myproperty能够从Foo中的其他方法访问 以下是我现在的做法: (function($){ $.fn.Foo = { main: function(){ return this.each(function(){ this.myproperty = 'abc'; ... ...bind('click', 'somemethod')... ... }); }
myproperty
能够从Foo中的其他方法访问
以下是我现在的做法:
(function($){
$.fn.Foo = {
main: function(){
return this.each(function(){
this.myproperty = 'abc';
...
...bind('click', 'somemethod')...
...
});
}
somemethod: function(e){
// access here myproperty
alert($.fn.Foo.myproperty);
}
}(jQuery));
(function($){
$.fn.extend({ Foo : $.fn.Foo.main});
}(jQuery));
而且似乎有效。但这是最好的方法吗?还有其他方法吗?可以通过Foo函数公开
(function($){
$.fn.Foo = {
main: function(){
return this.each(function(){
this.myproperty = 'abc';
...
...bind('click', 'somemethod')...
...
});
getmyproperty: function(){
var myproperty = 'abc';
return myproperty;
}
}
somemethod: function(e){
// access here myproperty
alert($.fn.Foo.getmyproperty());
}
}(jQuery));
我觉得你想上一堂课?您目前正在使用可以调用$(“#test”).Foo()等元素的函数扩展jQuery库 良好的启动设置是:
(function($) {
var methods = {
init: function(settings) {
var options = $.extend({}, $.fn.FooMe.defaults, settings);
$(this).data("settings", options);
$(this).bind("click", methods.myOtherFunction);
},
myOtherFunction: function() {
alert($(this).data("settings").you);
}
};
$.fn.FooMe = 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.Foo');
}
};
$.fn.FooMe.defaults = {
you: "default"
};
}(jQuery));
$("#test").FooMe({
you: "TADAA"
});