[英]Unable to access objects datamember, despite showing its exsistence in console.log. Attempted access returns undefined
I have a array of anonymous functions that are constructors, they take a parameter, then use it to build a var to this. 我有一个匿名函数数组,它们是构造函数,它们接受一个参数,然后使用它来为此构建一个变量。
var template = [
function (model){ this.html = "blah" + model.something},
function (model){ this.html = "blah" + model.something},
]
I loop through the array and construct each function into an object using the new keyword. 我遍历数组,并使用new关键字将每个函数构造为一个对象。
template.foreach( template => template = new template(model))
This seems to work because when I console.log it shows template as a list of objects with data member this.html, and its populated correctly. 这似乎可行,因为当我在console.log中将模板显示为带有数据成员this.html的对象列表时,模板已正确填充。
However, when I try to access template[0].html it returns undefined. 但是,当我尝试访问template [0] .html时,它返回未定义。
When I do typeof
on an element of the list it says function, yet the browser shows it as an object, and most importantly when I do template[0].html it returns as undefined despite showing it when I console log the list. 当我在列表中的元素上执行typeof
,它说的是功能,但浏览器将其显示为对象,最重要的是,当我执行template [0] .html时,尽管在控制台日志列表中显示了它,但它仍返回undefined。
it should be forEach()
instead of foreach()
应该是forEach()
而不是foreach()
You should always return something in your function. 您应该始终在函数中返回某些内容。
This is very strange way to use this
it is because when you store function in array, the this
is referencing the object where you call this function. 这是用非常奇怪的方式this
是因为当你存储功能的阵列中, this
是引用在这里你调用这个函数的对象。
The point is that forEach is not changing the array that is being iterated, it is just iterating it. 关键是forEach不会更改要迭代的数组,而只是对其进行迭代。 If you want to return an array of already created objects you can use other function like map: 如果要返回已创建对象的数组,则可以使用其他函数,例如map:
const myObjectArray = template.map(t => new t(model));
Now you can access myObjectArray[0].html 现在您可以访问myObjectArray [0] .html
Take care that myObjectArray is a new array and template is not changed. 注意myObjectArray是一个新数组,并且模板没有更改。
By the way, having a variable called template that holds an array is not a good practice, better call it templateArray or templates (make it clear that it is an array) 顺便说一句,有一个叫做template的变量来保存一个数组不是一个好习惯,最好将其称为templateArray或模板(清楚地说这是一个数组)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.