londondev londondev - 6 months ago 18
jQuery Question

Cannot init an object in jquery document.ready

I have an javascript object named

concept
:

function concept() {
this.ConceptId = 0;
this.Name = "";
}


I am trying to initiate it in jQuery
document.ready
:

$(document).ready(function() {
var concept = new concept;
});


It returns an error:


Uncaught TypeError: concept is not a constructor


If I move the object inside the
document.ready
, it is working.

$(document).ready(function() {
function concept() {
this.ConceptId = 0;
this.Name = "";
}
var concept = new concept;
});


I am still new on javascript, as far as I understood document.ready is run when DOM is completed. I don't understand why it cannot access the object which is defined out of the
document.ready
scope.

Here it is the fiddle: https://jsfiddle.net/49rkcaud/1/

Answer

The issue is because you're redefining concept. You just need to change the name of the variable:

$(document).ready(function() {
    var foo = new concept; // change the variable name here
    alert(foo.ConceptId); // = 0
});

function concept() {
    this.ConceptId = 0;
    this.Name = "";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments