[英]Cannot init an object in jquery document.ready
I have an javascript object named concept
: 我有一个名为
concept
的javascript对象:
function concept() {
this.ConceptId = 0;
this.Name = "";
}
I am trying to initiate it in jQuery document.ready
: 我试图在jQuery
document.ready
启动它。
$(document).ready(function() {
var concept = new concept;
});
It returns an error: 它返回一个错误:
Uncaught TypeError: concept is not a constructor
未捕获的TypeError:概念不是构造函数
If I move the object inside the document.ready
, it is working. 如果我在
document.ready
移动对象,它就可以了。
$(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. 我仍然是javascript的新手,据我所知,document.ready在DOM完成时运行。 I don't understand why it cannot access the object which is defined out of the
document.ready
scope. 我不明白为什么它无法访问
document.ready
范围中定义的对象。
Here it is the fiddle: https://jsfiddle.net/49rkcaud/1/ 这是小提琴: https : //jsfiddle.net/49rkcaud/1/
The issue is because you're redefining concept
. 问题是因为你正在重新定义
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>
Try this: 尝试这个:
Jsfiddle: https://jsfiddle.net/3w284mcs/ 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);
});
You just need to change variable
name where call this function. 您只需要在调用此函数的位置更改
variable
名称。
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 = "";
}
Better Approach 更好的方法
You should create object of function using ()
你应该使用
()
创建函数的对象
var objConcetp = new concept();
Also use constructor
rather than directly assigning values
. 还可以使用
constructor
,而不是直接分配values
。 Your function look like: 你的功能如下:
$(document).ready(function(){
var oConcept = new concept(1, "YourName");
});
function concept(conceptId, name){
this.ConceptId = conceptId;
this.Name = name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.