Why does this closure not work?

时间:2016-07-11 20:28:13

标签: javascript jquery

I have the following code in a .js file:

ElegirRegion = function () {
    var pagina = $('#pagina').val();
    carousel.setPaginaActual(pagina);
    var x1 = $('#x1').val();
    var y1 = $('#y1').val();
    var x2 = $('#x2').val();
    var y2 = $('#y2').val();
    this.SeleccionInicial = function () {
        if (!(x1 == 0 && x2 == 0 && y1 == 0 && y2 == 0)) {
            var ias = $('img.imagen').eq(pagina).imgAreaSelect({ instance: true });
            ias.setSelection(x1, y1, x2, y2);
            ias.setOptions({ show: true });
            ias.update();
        }
    }
    //more stuff
}
$(document).ready(ElegirRegion);

And in the .html file code that calls the SeleccionInicial function:

$(window).load(function(){
    ElegirRegion.SeleccionInicial();
});

However, when I try to call SeleccionInicial, I get a SeleccionInicial is not a function error! Why isn't SeleccionInicial a closure?

1 个答案:

答案 0 :(得分:1)

In your code, you're using this as though it reference ElegirRegion. But that's not what's happening.

ElegirRegion = function() {
  console.log(this === ElegirRegion);
  console.log(this.toString());
  console.log(this === document);
};

$(document).ready(ElegirRegion);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The only way that would happen is if you were treating that function as a constructor (ElegirRegion = new ...). Instead, if you want to add a method to ElegirRegion, then reference it directly.

ElegirRegion = function() {
  ElegirRegion.SeleccionInicial = function() {
    console.log('start');
  };
};

$(document).ready(ElegirRegion);

$(window).load(function() {
  ElegirRegion.SeleccionInicial();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>