简体   繁体   English

如何在JavaScript对象中调用函数?

[英]How to call a function inside a JavaScript object?

I'm trying to call the bar function inside foo but I can't seem to figure out how to do it. 我试图在foo调用bar函数,但似乎无法弄清楚该怎么做。 What am I missing or what am I not understanding? 我缺少什么或我不了解什么?

 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); } 

Change bar so that it is a property of foo : 更改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> 

you have a little oversight, inside on how to access to the bar method inside foo. 您对如何访问foo中的bar方法有一些疏忽。 So you need to return any from foo, will be an object and inside bar method. 因此,您需要从foo返回任何内容,这将是一个对象并在bar方法内部。 Here a demo , with a very little touched from yours: 这是一个演示 ,您的感动很少:

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);
}

two ways 两种方式

var foo = function(){
    return {
        bar: function(){ alert('bar')}
    };
};
jQuery.fn.mainfoo = function() {
    ///
    var mainfoo = foo();
    ///
};

other way 另一种方式

var foo = function(){
    this.bar = function() {
        alert('bar');
    }
};
$.fn.mainfoo = function() {
    var mainfoo = new foo();  
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM