![](/img/trans.png)
[英]How to Store call back function name inside javascript object and call
[英]How to call a function inside a JavaScript object?
我试图在foo
调用bar
函数,但似乎无法弄清楚该怎么做。 我缺少什么或我不了解什么?
var foo = function() { function bar() { alert('bar'); } }; $.fn.mainfoo = function() { alert('mainfoo'); return this.each(function(key, value) { if ($(this).data('mainfoo')) return $(this).data('mainfoo'); var mainfoo = new foo(); $(this).data('mainfoo', mainfoo); }); }; var myfoo = $('body').mainfoo(); try { myfoo.data('mainfoo').bar(); } catch (e) { alert(e); }
更改bar
,使其成为foo
的属性:
var foo = function(){ this.bar = function() { alert('bar'); } }; $.fn.mainfoo = function() { alert('mainfoo'); return this.each(function(key, value){ if ($(this).data('mainfoo')) return $(this).data('mainfoo'); var mainfoo = new foo(); $(this).data('mainfoo', mainfoo); }); }; var myfoo = $('body').mainfoo(); myfoo.data('mainfoo').bar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您对如何访问foo中的bar方法有一些疏忽。 因此,您需要从foo返回任何内容,这将是一个对象并在bar方法内部。 这是一个演示 ,您的感动很少:
var foo = function(){
return {
bar: function() {
alert('bar');
}
}
};
$.fn.mainfoo = function() {
console.log('mainfoo');
return this.each(function(key, value){
if ($(this).data('mainfoo')) return $(this).data('mainfoo');
var mainfoo = new foo();
$(this).data('mainfoo', mainfoo);
});
};
var myfoo = $('body').mainfoo();
try{
myfoo.data('mainfoo').bar();
}catch(e){
console.log(e);
}
两种方式
var foo = function(){
return {
bar: function(){ alert('bar')}
};
};
jQuery.fn.mainfoo = function() {
///
var mainfoo = foo();
///
};
另一种方式
var foo = function(){
this.bar = function() {
alert('bar');
}
};
$.fn.mainfoo = function() {
var mainfoo = new foo();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.