未捕获的引用错误,带有对象构造函数实例的Javascript

时间:2019-02-08 20:36:20

标签: javascript jquery string object

无法从我的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实例,即可正常工作。有些事情我做的不正确/不理解。

1 个答案:

答案 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);

});