Emin Çiftçi Emin Çiftçi - 14 days ago 6
Javascript Question

How to run a subfunction which is element of an array in jquery

I try to reach a subfuntion that is element of an array.

In the below example we can reach the

name
property like
window['name']
.

But if property is a function it can not be called like this. What I try to do is in
.each
function if item is a function run the function. How can I do that ?.

$(document).ready(function() {

var human = {
name: 'Emin',
surname: 'Çiftçi',
job: 'Software Developer',
func: function() {
alert(name + ' ' + surname + ', ' + job);
}
};

$.each(human, function(index, item) {
//if(item is a function) {
// run the function
//}
$('<div>').text(index + ': ' + item).appendTo('#deneme');

});
});



Answer

Use typeof

PS: You also need to fix the name, surname and job in the alert

$(document).ready(function() {

  var human = {
    name: 'Emin',
    surname: 'Çiftçi',
    job: 'Software Developer',
    func: function() {
      alert(human.name + ' ' + human.surname + ', ' + human.job);
    }
  };

  $.each(human, function(name, item) {
    console.log(typeof item);
    if (typeof item == "function") item();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Comments