- Full-Stack Vue.js 2 and Laravel 5
- Anthony Gore
- 159字
- 2021-07-02 19:57:21
Getters and setters
To assign a value to a property of a JavaScript object is as simple as:
var myObj = { prop: 'Hello' }
To retrieve it is just as simple:
myObj.prop
There's no trick here. The point I want to make though, is that we can replace this normal assignment/retrieval mechanism of an object through use ofgetters and setters. These are special functions that allow custom logic for getting or setting the property's value.
Getters and setters are especially useful when one property's value is determined by another. Here's an example:
var person = { firstName: 'Abraham', lastName: 'Lincoln', get fullName() { return this.firstName + ' ' + this.lastName; }, set fullName(name) { var words = name.toString().split(' '); this.firstName = words[0] || ''; this.lastName = words[1] || ''; } }
Thegetandsetfunctions of thefullNamepropertyare invoked whenever we attempt a normal assignment/retrieval of its value:
console.log(person.fullName); // Abraham Lincoln person.fullName = 'George Washington'; console.log(person.firstName); // George console.log(person.lastName) // Washington
推薦閱讀
- Practical Data Analysis Cookbook
- Facebook Application Development with Graph API Cookbook
- OpenShift開(kāi)發(fā)指南(原書(shū)第2版)
- 羅克韋爾ControlLogix系統(tǒng)應(yīng)用技術(shù)
- C語(yǔ)言程序設(shè)計(jì)實(shí)訓(xùn)教程
- Python高效開(kāi)發(fā)實(shí)戰(zhàn):Django、Tornado、Flask、Twisted(第3版)
- JSP開(kāi)發(fā)案例教程
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- Python:Master the Art of Design Patterns
- C語(yǔ)言課程設(shè)計(jì)
- Getting Started with Laravel 4
- 好好學(xué)Java:從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- Spring MVC+MyBatis開(kāi)發(fā)從入門(mén)到項(xiàng)目實(shí)踐(超值版)
- Apache Camel Developer's Cookbook
- Hadoop 2.X HDFS源碼剖析