- 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
推薦閱讀
- C++ Builder 6.0下OpenGL編程技術
- 控糖控脂健康餐
- 少年輕松趣編程:用Scratch創作自己的小游戲
- Android 9 Development Cookbook(Third Edition)
- SEO智慧
- INSTANT Passbook App Development for iOS How-to
- Java面向對象程序設計
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- Apache Camel Developer's Cookbook
- 現代C:概念剖析和編程實踐
- Python編程基礎教程
- Java核心編程
- 軟件再工程:優化現有軟件系統的方法與最佳實踐
- 計算機視覺實戰:基于TensorFlow 2
- C語言開發寶典