简体   繁体   English

jQuery创建一个简单的对象,添加属性并访问它

[英]jQuery creating a simple object, adding properties and accessing it

// jquery 2.1.3 imported

var testarray = [];

var newTAelement = TAelement( "rs5", "Thirteen", "13", "15", "14","11","99");

function TAelement(category, question, trueanswer, c1, c2, c3, c4 )
{
    this.category = category;
    this.question = question;
    this.trueanswer = trueanswer;
    this.c1 = c1;
    this.c2 = c2;
    this.c3 = c3;
    this.c4 = c4;
}

testarray.push(newTAelement);

elementextracted = testarray[0];

alert(elementextracted.category);

I want to create the object that has the above properties 我想创建具有上述属性的对象

I want to store the value named "rs5" in the "category" property 我想将名为“ rs5”的值存储在“类别”属性中

And then add it to the array named testarray 然后将其添加到名为testarray的数组中

And then access it. 然后访问它。

I want to see the alert that says "rs5" but I am not seeing it. 我想看到显示“ rs5”的警报,但没有看到。

What did I do wrong? 我做错了什么? Thanks a lot Stack Overflow! 非常感谢Stack Overflow!

You called the constructor function as if it were a regular function. 您调用了构造函数,就好像它是常规函数一样。 This meant that the default value of this was (in a browser, outside of strict mode) window and not a new object. 这意味着,默认值this是(在浏览器中,严格模式外) window一个新的对象,而不是。 It also means that the default return value was undefined instead of that new object. 这也意味着默认返回值是undefined而不是该新对象。

To use it as a constructor you need to use the new operator . 要将其用作构造函数,需要使用new运算符

var newTAelement = new TAelement( "rs5", "Thirteen", "13", "15", "14","11","99");

NB: This has nothing at all to do with jQuery, which you don't use anywhere in your code. 注意:这与jQuery完全无关,您在代码中的任何地方都不会使用它。 It is core JavaScript. 它是核心JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM