[英]Can't access object property in javascript variable
I've struggled for a while seek for help. 我努力争取了一段时间。 This is really strange. 这真是奇怪。 I want to access an object property, but this always throws an error: 我想访问一个对象属性,但这总是抛出错误:
TypeError : cannot read property template of undefined TypeError:无法读取未定义的属性模板
But my application works properly. 但是我的应用程序正常工作。 Just there is notification output if can't access template of undefined 如果无法访问未定义的模板,则只有通知输出
//this is my object variabel var login = {}; login.data = { checkInput : formValidation, userSchema : User, template : 'pages/users/login', } // so I add new method which I call in different files login.header = async(req, res, next) => { /// in this section function I want to read property of template but it always return undefined try { // I have some code with read databases here //some data i want to render var data = {}; res.render(this.data.template,data); // I've been also trying another way. var template = login.data.template !== undefined ? 'page/users/login' : login.data.template; res.render(login.data.template, data); // both of above always return output, but can't read template of undefined } catch(e) { throw new Error(e); } }
It's because you're using an arrow function which loses the binding to login
(the this
you're accessing is an attempt to access the login
object). 这是因为你使用的失去结合箭头功能login
(在this
你所访问的访问尝试login
对象)。 Use a regular ES5 function. 使用常规的ES5功能。
login.header = async function(req, res, next) {...};
As found in the docs : 如在文档中找到的:
An arrow function expression is a syntactically compact alternative to a regular function expression , although without its own bindings to the
this
,arguments
,super
, ornew.target
keywords. 箭头函数表达式在语法上是常规函数表达式的紧凑选择,尽管没有与this
,arguments
,super
或new.target
关键字的绑定。 Arrow function expressions are ill suited as methods, and they cannot be used as constructors. 箭头函数表达式不适合用作方法,并且不能用作构造函数。
i've been trying to access with property with no array function 我一直在尝试使用没有数组功能的属性进行访问
var login = {} login.data = { template : 'admin/pages/' body : {} }; login.getViews = function(req, res, next) { // it'l throw an error res.render(this.data.template, this.data.body); // than i try with another way, it works res.render(login.data.template, login.data.body); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.