基于其他属性定义对象属性值

Defining an object property value based on other property

本文关键字:属性 定义 对象 其他 于其他      更新时间:2023-09-26

当执行以下代码时,我得到这个错误:

Uncaught TypeError: Cannot read property 'theTests' of undefined

$(document).ready(function() {
  var Example = {};
  Example = {
    settings: {
      theTests: $('.test'),
      firstTest: Example.settings.theTests[0]
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

但是如果我这样做:

$(document).ready(function() {
  var Example = {};
  Example = {
    settings: {
      theTests: $('.test'),
      firstTest: $('.test')[0]
    },
    test: function() {
      var theTests = $('.test'),
        firstTest = theTests[0]
    }
  }
  Example.test();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

在设置中定义它,或者在函数中定义它,它们都是这样工作的。

所以我的问题是:

为什么根据settings内部的theTests属性定义firstTest属性时不起作用?

编辑:

我检查了这个问题,但我不寻找一种方法来做到这一点。我想知道为什么它不起作用

我同意-它不完全是重复的,因为你问的是为什么-而不是如何。

不能这样做的原因在错误中给出-您引用的对象尚未定义。当您将空对象分配给Example时,您将立即尝试将其设置为其他对象。请注意,这将首先从最内层的项求值,即它将做:

  • 设置Example为以下结果:
    • 创建一个对象,它包含:
      • settings属性,这是以下操作的结果:
        • 创建一个具有两个属性的对象:
          • theTests:设置为$(.test)
          • firstTest:设置为Example.settings.theTests[0]

在最后一行中,请注意我们还没有分配settings对象(我们仍然在定义将分配给settings的对象的属性),因此在该行运行时它是未定义的。

在第一个示例中,您试图在示例完全初始化之前访问示例的属性。

你可以这样做

$(document).ready(function() {
  var tests = $('.test');
  var Example =  {
    settings: {
      theTests: tests,
      firstTest: tests[0]
    },
    test: function() {
      var theTests = $('.test'),
        firstTest = theTests[0]
    }
  }
  Example.test();
});

尝试:

var Example = new function(){
    this.settings = {theTests:  $('.test')};
    this.settings.firstTest = this.settings.theTests[0];
    this.test = function(){
        console.log(this.settings.theTests);
        console.log(this.settings.firstTest)
    };
};
Example.test();

您正在尝试访问在该特定时间未定义的变量属性。

Example.settings将在Example初始化后可用。

var Example = {};
var theTests = $('.test');
Example = {
  settings: {
    theTests: theTests,
    firstTest: theTests[0]
  }
}

这段代码的第二行将:

  1. 创建对象
  2. 将对象赋值给变量
 var Example = {};
  Example = {
    settings: {
      theTests: $('.test'),
      firstTest: Example.settings.theTests[0] //theTests does not exist
    }
  }


 Example = {
    settings: {
      theTests: $('.test'),
      firstTest: $('.test')[0]
    },
    test: function() {
      var theTests = $('.test'), // theTests has been defined
        firstTest = theTests[0]  // and used here
    }
  }