无法从我的Javascript文件创建对象构造函数的实例:
$(document).ready(function() {
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
persons = ['a']
});
文件正在加载,在Chrome JS控制台中,调用person数组没有问题,它存在于作用域中。
但是,
var myFather = new Person("John", "Doe", 50, "blue");
给予
Uncaught ReferenceError: Person is not defined
先粘贴Person构造函数,然后在Chrome JS控制台中粘贴myFather实例,即可正常工作。有些事情我做的不正确/不理解。
答案 0 :(得分:0)
最有可能是因为您在if (operator === "+") {
strength += 2;
final.base += Math.min(40, 4 * strength);
} else if (operator === "-") {
final.base -= Math.min(40, 4 * strength);
strength -= 2;
}
内部声明了Person
构造函数,而在外部使用了它。 $(document).ready
构造函数将位于Person
的回调的本地。在$(document).ready
之外声明Person
构造函数,但在内部使用它:
$(document).ready
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var persons = ['a'];
$(document).ready(function() {
var myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather);
});