io.socket is undefined inside function declaration, defined outside it

So I'm trying to use io.socket to make a POST call to some controller action. The strange thing is that, when I use io.socket.someMethod() inside script tags like such, it works fine:

<script>
io.socket.post('/visualization/star', { id: visualID }, function (resData, jwres) {
  var star = document.getElementById("star-" + visualID.toString());
  if (star.className == "gold-star glyphicon glyphicon-star-empty md") {
    star.className = "grey-star glyphicon glyphicon-star-empty md";
  } else {
    star.className = "gold-star glyphicon glyphicon-star-empty md";
  }
});
</script>

But putting it inside a function declaration renders io.socket to be undefined:

<script>
function starVisual(visualID) {
  io.socket.post('/visualization/star', { id: visualID }, function (resData, jwres) {
    var star = document.getElementById("star-" + visualID.toString());
    if (star.className == "gold-star glyphicon glyphicon-star-empty md") {
      star.className = "grey-star glyphicon glyphicon-star-empty md";
    } else {
      star.className = "gold-star glyphicon glyphicon-star-empty md";
    }
  });
}
</script>

Putting alert(io.socket) outside the function declaration results in an object, while putting it on the first line inside the function declaration results in undefined.

I've also tried window.io.socket, but that results in the same thing. The JS file sails.io.js is included and loaded properly at the beginning, when the page first loads through my layouts.ejs. Also tried doing <script>window.io = io</script> to no avail.

I'm putting it inside a function declaration so that I can use it as part of my onclick attribute upon clicking an icon: <td class="star-wrap"><span id="star-<%= visualization.id %>" class="grey-star glyphicon glyphicon-star-empty md" onclick="starVisual(<%= visualization.id %>).bind(this);"></span></td>

Any help would be much appreciated!

I've setup my functions like yours and everything seems happy.

The problem may be a race condition. The sails.io script is loaded at the bottom of the body (make sure you place your scripts under that). If you console.log() anything before the scripts loads, you will get undefined errors.

If anyone runs into this problem, for future reference, I solved this problem by doing the following:

<script>
window.socket = socket.io
function starVisual(visualID) {
io.socket.post('/visualization/star', { id: visualID }, function (resData, jwres) {
  var star = document.getElementById("star-" + visualID.toString());
  if (star.className == "gold-star glyphicon glyphicon-star-empty md") {
    star.className = "grey-star glyphicon glyphicon-star-empty md";
  } else {
    star.className = "gold-star glyphicon glyphicon-star-empty md";
    }
  });
}
</script>