Cannot start object in jquery document.ready

I have a javascript object named concept :

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

I am trying to run 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 an object inside document.ready , it works.

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

I'm still new to javascript, as far as I understand document.ready gets started when the DOM is completed. I do not understand why it cannot access the object that is defined from the document.ready scope.

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

+7
javascript jquery
source share
3 answers

The problem is that you are redefining the concept . You just need to change the variable name:

 $(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> 
+4
source share

Try the following:

Jsfiddle: https://jsfiddle.net/3w284mcs/

  $(document).ready(function() { var concept = function() { this.ConceptId = 0; this.Name = ""; } var concept_obj = new concept(); alert(concept_obj.ConceptId); }); 
+4
source share

You just need to change the name of the variable where this function is called.

Answer

  $(document).ready(function() { /*function concept() { this.ConceptId = 0; this.Name = ""; }*/ var concept1 = new concept; alert(concept1.ConceptId); }); function concept() { this.ConceptId = 5; this.Name = ""; } 

Best approach

You must create a function object using ()

 var objConcetp = new concept(); 

Also use constructor instead of directly assigning values . Your function looks like this:

 $(document).ready(function(){ var oConcept = new concept(1, "YourName"); }); function concept(conceptId, name){ this.ConceptId = conceptId; this.Name = name; } 
+3
source share

All Articles