[英]Getting undefined setting object's property value using this in javascript
I was trying to set fullname
property of the object person
using this
, but got undefined when logging out the full name. 我试图使用this
设置对象person
fullname
属性,但是注销全名时未定义。
var person = {
name:'yask',
fullname: this.name + ' Srivastava'
}
console.log(person.fullname);
This is strange, as using this
while using inside the function refers to the object. 这很奇怪,因为使用this
使用函数的内部,而指的是对象。 Here it looks like it's being referred to global object.(Window maybe..?) 在这里看起来像是在引用全局对象。(也许是窗口?。?)
You can do it with the use of getter , 您可以使用getter来做到这一点,
var person = {
name:'yask',
get fullname(){ return this.name + ' Srivastava' }
}
console.log(person.fullname);
Basically the this
in your case will point the context of
lexical scope
the function of the object, not the object itself. 基本上,在您的情况下, this
将指向
词法范围
的上下文对象的功能,而不是对象本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.