简体   繁体   中英

Javascript: calling function inside another function not working?

So inside my <script> tags, I have these functions.

$.fn.getRandom = function(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

function placeRandom() {
    alert(getRandom(1,7));
}

and I call the placeRandom() function like so

$(document).ready(function() {
    placeRandom();
});

when I do this, it gives me an

Object expected

error and refers to the line where I wrote

alert(getRandom(1.7));

Now, my main question is if there is anything wrong with the code which I am showing you, or does it look correct? Because if it looks correct then I think i'm going to have to run through the rest of my entire code and look for maybe a open bracket which isn't closed because that might be the problem. So yea, is there any problem with my placeRandom() or getRandom() function or is the error occuring because of another reason other than these functions?

The problem is were you are defining the getRandom function. You are putting it in the jQuery.fn namespace. If you organize your code like the following it should work much better.

var getRandom = function(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

var placeRandom = function() {
    alert(getRandom(1,7));
}

$(document).ready(function() {
    placeRandom();
});

Additional Info: jQuery.fn is actually a prototype but is commonly referred to as a namespace in this specific context.

You are binding getRandom to the jQuery namespace, you will only be able to access it through a jQuery object instance or via $.fn.getRandom()

So unless you want to be able to call it like $(selector).getRandom() , just declare it as a standard function.

you are binding getRandom to the $ namespace (jQuery). so you have to call it $.fn.getRandom(1,7) or define the function the following:

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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