文档章节

JavaScript Getter And Setter

yunfound
 yunfound
发布于 2015/01/20 18:37
字数 735
阅读 298
收藏 4

JavaScript Getters and Setters 23 December 2013 by Jack Franklin For the most part, in JavaScript, what you see is what you get. A value's a value; there are no tricks. Sometimes however, you want a value that's based on some other values: someone's full name, for example, is a concatenation of their first and last names. If you have a person object, and you want the users of that object to be able to set the full, first or last name, and see that change immediately reflected in the other values, you'd conventionally build it with functions:

person.setLastName('Smith'); person.setFirstName('Jimmy'); person.getFullName(); // Jimmy Smith But this is ugly, and requires the users of your object to care that the properties are related; in a more complex example, that might not be as obvious as with names. Luckily, there's a better way, added in ECMAScript 5.

Meet getters and setters.

How

Let's make that person object. We want to be able to set the first name, last name or full name, and have it update the other two automagically.

var person = { firstName: 'Jimmy', lastName: 'Smith', get fullName() { return this.firstName + ' ' + this.lastName; }, set fullName (name) { var words = name.toString().split(' '); this.firstName = words[0] || ''; this.lastName = words[1] || ''; } }

person.fullName = 'Jack Franklin'; console.log(person.firstName); // Jack console.log(person.lastName) // Franklin So what's going on here?

The get and set keywords are important. Following them is the property they relate to (fullName) and a function body that defines the behaviour when the property is accessed (name = person.fullName) or modified (person.fullName = 'Some Name').

These two keywords define accessor functions: a getter and a setter for the fullName property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set. It's up to you what you do with that value, but what is returned from the setter is the value that was passed in – so you don't need to return anything.

The official way: Object.defineProperty

Along with the inline method of declaring getters and setters, it can also be done more explicitly via Object.defineProperty (MDN Documentation). This method takes three arguments. The first is the object to add the property to, the second is the name of the property, and the third is an object that describes the property (known as the property's descriptor). Here's an example that replicates the above example:

var person = { firstName: 'Jimmy', lastName: 'Smith' };

Object.defineProperty(person, 'fullName', { get: function() { return firstName + ' ' + lastName; }, set: function(name) { var words = name.split(' '); this.firstName = words[0] || ''; this.lastName = words[1] || ''; } }); The advantage here isn't immediately apparent. Other than being able to add properties after creating the initial object, is there a real benefit?

When you define a property this way, you can do much more than just define a setter or getter. You may also pass following keys:

configurable (false by default): if this is true, the property's configuration will be modifiable in future. enumerable (false by default): if true, the property will appear when looping over the object (for (var key in obj)). We can also define properties that don't have explicit getters or setters:

Object.defineProperty(person, 'age', { value: 42 }); This will create person.age, and set it to the value 42. It's important to note that this property isn't writable. Calling person.age = 99 will have no effect. In this way you can create read-only properties. If a property has a value key set, it cannot have a getter or setter. Properties can have values or accessors, not both.

Not only that, but because the enumerable property defaults to false, this property will not appear when we loop over the object's keys.

If we wanted to make a property writable, we would need to set the writable property:

Object.defineProperty(person, 'age', { value: 42, writable: true }); Now, person.age = 99; will have the desired effect.

Overuse

Remember: just because a feature exists, it doesn't need to be used all the time. Getters and Setters have their use cases, but don't go over the top, or you'll most likely end up with a design that's confusing for those interacting with your objects. Used carefully, they're very powerful. But with great power comes great responsibility.

Browser support?

IE9 and above have full support for Object.defineProperty, along with Safari 5+, Firefox 4+, Chrome 5+ and Opera 12+. If you’re working with Node.js, there's full support. Don't you just love Node?!

本文转载自:

yunfound
粉丝 30
博文 16
码字总数 2655
作品 0
上海
架构师
私信 提问
[转]__defineGetter__ 和 __defineSetter__

原文: http://www.javaeye.com/topic/40946 IE 不支持 __defineGetter__ 和 __defineSetter__ Getter是一种获取一个属性的值的方法,Setter是一种设置一个属性的值的方法。可以为任何预定义...

长平狐
2012/06/25
289
0
cheerp 如何使用回调的回答

关于如何使用callback方法的问题很好理解,现在比较时尚的语言里都支持异步编程,事件消息或者回调。 这应该是无关优雅的, 在cheerp中你可以使用javascript一样的思维来考虑问题, 这一切编...

钟元OSS
01/09
0
0
[译]继承 JavaScript 类中的静态属性

原文地址:Static Properties in JavaScript Classes with Inheritance 原文作者:Valeri Karpov 译文出自:掘金翻译计划 本文永久链接:github.com/xitu/gold-m… 译者:Augustwuli 校对者:...

程序媛_小发
2018/12/25
0
0
说说 Vue.js 的计算属性

1 应用场景 Vue.js 的表达式如果因为逻辑复杂变得过长时,就会变得臃肿,以至于难以阅读和维护。 这里我们对一个以分号分隔的字符串做逆序处理,并修改分隔符为逗号的表达式。 html: js: ...

deniro
2018/10/28
0
0
面向对象(理解对象)——JavaScript基础总结(一)

定义 无序属性的集合(散列表),其属性可以包含基本值,对象或函数; 每个对象都是基于一个引用类型创建的,这个引用类型可以是原生类型,也可以是自定义类型。 创建对象 创建一个Object实例...

萌小萌和她的前端笔记
04/01
0
0

没有更多内容

加载失败,请刷新页面

加载更多

centos7 新手阿里云服务器安装mongodb

简介 MongoDB 是一个基于分布式 文件存储的NoSQL数据库 由C++语言编写,运行稳定,性能高 旨在为 WEB 应用提供可扩展的高性能数据存储解决方案 MongoDB特点 模式自由 :可以把不同结构的文档存...

醉雨
16分钟前
1
0
sql注入漏洞,应屏蔽SQL注入攻击

注:SQL注入好比是前端URL传参数请求时参数以SQL 做为参数传入,如 select 1 from dual where 1=1 or 1=1 and 1=2;(类似这样的SQL语句) 防御方法 如果自己编写防注代码,一般是先定义一个函...

颜丽
16分钟前
1
0
装饰者模式

 代理模式与装饰者模式看起来很像,都实现基础对象实现的接口,在其自身对象中都保存着对被代理/被装饰者的对象引用。   先来看看装饰者模式的定义:动态的将责任附加到被装饰者对象上,用...

铁骨铮铮
20分钟前
0
0
我为什么飞行 10000 公里去西班牙参加 KubeCon?

2019 年 5 月 20 日至 23 日, 由 Cloud Native Computing Foundation (CNCF) 主办的云原生技术大会 KubeCon + CloudNativeCon EU(欧洲场)即将在热情洋溢的巴塞罗那盛装启幕。 作为云计算领...

zhaowei121
38分钟前
0
0
Node.getTextContent() not found 解决办法【不需要调整builder path下面包顺序】

新导入的工程,w3c的getTextContent找不到,response的setCharacterEncoding找不到,网上很多教程都是“调整工程builder path的lib包顺序把jre、tomcat调到上面即可”,但是进入项目的build...

嘿嘿嘿IT
45分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部