-7

how to check if a function exists?

accepted answer here but it doesn't work

function sb_save(){
alert('saving');
}

$('button').on('click', function(){
 if ($.fn.sb_save){sb_save();}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
qadenza
  • 9,025
  • 18
  • 73
  • 126

3 Answers3

2

function sb_save(){
alert('saving');
}

$('button').on('click', function(){
 if (typeof sb_save==="function"){
sb_save();
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
Asutosh
  • 1,775
  • 2
  • 15
  • 22
0

function sb_save(){
    alert('saving');
}

$('button').on('click', function(){
    if (typeof sb_save === 'function') {
        sb_save();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
Maestro
  • 865
  • 1
  • 7
  • 24
-1

Given the code example you show, you are trying to check if jQuery has been extended using that function:

if ($.fn.sb_save)

The way you're trying to call the function

sb_save();

shows this is not what you intended.

Instead, to simply check if sb_save is an executable object (a.k.a. function), use the most upvoted answer from the question you linked:

if (typeof sb_save === 'function')

function sb_save() {
  alert('saving');
}

$('button').on('click', function() {
  if (typeof sb_save === 'function') {
    sb_save();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
connexo
  • 53,704
  • 14
  • 91
  • 128