JQuery - function call function from another function variable

Why this does not work:

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

?

I get foo - undefined error. But I just defined it above ...

+4
source share
6 answers

You just need to call foo (), not el.foo (). (If I am missing something about how you use this.)

+3
source

Since foo is not a function defined / attached to el, you cannot call foo from el context. You need to call foo directly.

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

However, if you need to call foo attached to el context, try the following:

 var boo = function() { ... foo.call(el);//This calls foo in el context } 
+3
source

If you understand 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(); } 
+3
source

Because foo not a property of el . This is a variable.

You will need:

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

This would work if you had:

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

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

  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. } 
+2
source

I assume that if you are trying to call:

  el.foo() 

Then el is a 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 name it without 'el':

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

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1337683/


All Articles