我有一个名为 concept
的 javascript 对象:
function concept() {
this.ConceptId = 0;
this.Name = "";
}
我正在尝试在 jQuery document.ready
中启动它:
$(document).ready(function() {
var concept = new concept;
});
它返回一个错误:
Uncaught TypeError: concept is not a constructor
如果我将对象移动到 document.ready
中,它就可以工作了。
$(document).ready(function() {
function concept() {
this.ConceptId = 0;
this.Name = "";
}
var concept = new concept;
});
我对 javascript 还是个新手,据我所知,document.ready 在 DOM 完成时运行。我不明白为什么它不能访问在 document.ready
范围内定义的对象。
这是 fiddle :https://jsfiddle.net/49rkcaud/1/
最佳答案
问题是因为您正在重新定义概念
。您只需要更改变量的名称:
$(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>
关于javascript - 无法在 jquery document.ready 中初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37208790/