简体   繁体   中英

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.

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. Here it looks like it's being referred to global object.(Window maybe..?)

You can do it with the use of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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