如果 Value 为真,则创建对象的新实例

If Value is true, create a new instance of an object

根据将用户输入值与随机值进行比较的 if 语句结果创建对象的新实例。如果为真,我希望它创建一个对象的新实例,并在每次比较结果为真时都这样做。

object.create() 是这样做的方法吗?

 var firstthing = new thing();

 function createnewthing()
 {
    var entry = document.getElementById('theirentry').value;
    if (oneobjectinaclass == "type1")
    var firstvalueinarray = type1[0];
    else if (oneobjectinaclass == "type2")
    var firstvalueinarray = type2[0]; 
    else if (oneobjectinaclass == "type3")
    var firstvalueinanarray = type[0];
    if (variableassignedtowhichevertype[1] == avaluetocompare)
    {
        numCorrect++;
        alert('You\'re right! ' + numCorrect); 

        //the code I'm trying to get to accomplish this goes here
        //var createanotherthingeachtimethisistrue = new Thing();

    }
    else {
        alert('Wrong!');
    }
}

你的问题出在作用域的概念上,JavaScript简单来说就是基于函数。

因此,为了解决您的问题,您可以通过键入

来分配当前范围之外的变量
value = new Thing();

其中值是先前在当前函数之外的一些函数上下文中创建的变量。


要深入挖掘,我们需要了解 JavaScript 中的作用域。有关更多详细信息,请参阅 Todd Motto 的 Scope (computer science) and for more insight into the matter, Everything you wanted to know about JavaScript scope 详细介绍。

简而言之;每当我们进入一个函数时,作用域就是 "created",而每当我们创建或访问变量时,都会使用该作用域的环境框架。如果变量不可用,则使用外部上下文(或环境框架)。所以举个例子。

示例 1

var toy = 'stick';
function changeToy() {
   var toy = 'ball';
}
changeToy();

与示例 2 相比

var toy = 'stick';
function changeToy() {
   toy = 'ball';
}
changeToy();

在示例 1 中,将创建并分配一个新的 变量,因为环境框架是函数 changeToy 的本地变量。在示例 2 中,变量 toy 在 changeToy 的环境框架中未找到,因此使用外部上下文(在本例中为全局上下文);在其中找到并重新分配变量。