开发者

What this "get" in JavaScript object means?

Look at this script:

var human = 
{
   firstName: 'Saeed',
   lastName: 'Ne开发者_高级运维amati',
   get fullName() {
       return this.firstName + ' ' + this.lastName;
   }
}

I don't know what get means in this context.


It identifies an object property that's returned when the property is read.

See https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/get


It´s a property. You can use it like this:

console.log(human.fullName); //Saeed Neamati

It´s a function that is called when accessing this property, and returns the value.

There are also setters available:

var human = 
{
   firstName: 'Saeed',
   lastName: 'Neamati',
   get fullName() {
       return this.firstName + ' ' + this.lastName;
   }
   set fullName(val) {
       var parts = val.split(' ');
       this.firstName = parts[0];
       this.lastName = parts[1];
   }
}

human.fullName = "Henry Miller";

But as cool as it might be, it´s not supported by all browsers. So it might be better avoid using it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜