4

Why doesn't this work:

  var foo = function() {
     ...
  };

  var boo = function() {
     ... 
     el.foo();
   }

?

I get a foo is undefined error. But I just defined it above...

2
  • Call it: foo() instead of el.foo() Commented Jan 30, 2011 at 18:44
  • I'm guessing there's some important context we're missing. el.foo() doesn't work here because (from what I can see) you don't create foo as a method of the object el - you create a normal variable. Commented Jan 30, 2011 at 18:45

6 Answers 6

3

You just need to call foo(), not el.foo(). (Unless I'm missing something about how you're using this.)

Sign up to request clarification or add additional context in comments.

Comments

3

If I understand you correctly, you need to create a jQuery plugin function:

jQuery.fn.foo = function(){
    return this.each(function(){
        // element-specific code here
    });
};

var boo = function() {
     ... 
     el.foo();
}

Comments

3

Since foo is not a function defined/attached to el hence you can't call foo from el's context. You need to call foo directly.

  var foo = function() {
     ...
  };

  var boo = function() {
     ... 
     foo();
   }

However if you need to call foo attached to el's context then try this:

var boo = function() {
         ... 
         foo.call(el);//This calls foo in el's context
       }

Comments

2

Because foo isn't a property of el. It's a variable.

You'd need:

var foo = function() {
   //...
};

var boo = function() {
   //... 
   foo();
}

It would work if you had:

var el = {};
el.foo = function() {
    // ...
};

var boo = function() {
   //... 
   el.foo();
}

Comments

2

In this instance it looks like foo() is a not a property of the object el. You defined the function, but from the example shown, it is probably a global function. If you want foo() to work on the variable el, then pass it to the function, like so:

 var foo = function(element) {
     //do something with this element
  };

 var boo = function() {
     ... 
     foo(el); //pass el into the foo function so it can work on it.
 }

Comments

1

I assume, if you are trying to call:

 el.foo()

Then el is jQuery object, something like

 var el = $("#smth");
 el.foo();

In this case you need to define 'foo' as:

$.fn.foo = function() {
....
}

Otherwise, if you are just trying to call 'foo' from 'boo', then just call it without 'el':

var foo = function() {
 ...
};

var boo = function() {
  ... 
  foo();
}

Hope, it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.