CocosCreator开发中为什么get/set如此重要?
摘要
我们都知道 CocosCreator 支持 get/set 方法,但是实际开发中很多小伙伴们并不常用。那么 get/set 到底能起到什么样的作用呢?我们从几个小故事说起!
正文
案例
案例一
一个项目中,你负责分数管理功能。这个分数只能由你写的代码修改! 你的同事小张却没有提前知道这件事,看到你写的
public score: number = 0;
就写了好几个修改方法,后来经过沟通,又是一顿大改。
案例二
一个项目中,你负责分数显示功能。提交代码后却出了很多问题! 你的同事小张在游戏逻辑那里直接读取你写的
public score: number = 0;
然后再写入 score 这个变量。但是它的游戏逻辑出了问题,出现了负数。
案例三
在一个项目中,你单独负责游戏制作,你在修改分数时,总是这样写
this.score += 1; this.getComponent(cc.Label).string = this.score + ;
你心想:如何做到只修改 this.score 就起到显示作用呢?
get/set的写法
JavaScript
cc.Class({ extends: cc.Component, properties: { score: { get: function () { return this._score; }, set: function (value) { this._score = value; } } }, onLoad () { }, });
TypeScript
const {ccclass, property} = cc._decorator; @ccclass export default class Score extends cc.Component { private _score: number = 0; @property get score () { return this._score; } set score (value) { this._score = value; } public onLoad (): void { } }
你可能会说,这跟直接写有什么区别吗? 别急,我们往下看!
只读方案
将 set 注释掉 TypeScript
const {ccclass, property} = cc._decorator; @ccclass export default class Score extends cc.Component { private _score: number = 0; @property get score () { return this._score; } // set score (value) { // this._score = value; // } public onLoad (): void { this.score += 1; } }
发现报错了。因为没有了 set 就不能进行写操作了。 read-only 只读 这样我们就解决了案例一的问题。
限制修改
我们都知道,正常分数都是正的。 在 set 方法中加以限制
set score (value) { // 最低为 0 分 if (value < 0) value = 0; this._score = value; }
这样你在代码里或编辑器里改它,只要小于零,自动修正。 这样我们就解决了案例二的问题。
MVVM实现
什么是 MVVM ? Model-View-ViewModel 数据与显示通过 ViewModel 联系起来。 简单理解就是,数据与显示绑定,数据变显示变,显示变数据变。 这与 get/set 有什么关系?关系大了! 记得刚刚讲的案例三吧,他所需要的就是数据到显示的一个单向绑定。 TypeScript
set score (value) { this._score = value; this.getComponent(cc.Label).string = this._score + ; }
数据变显示变
双向绑定怎么实现呢?我们用一个编辑框组件(cc.EditBox)举例。 TypeScript
const {ccclass, property} = cc._decorator; @ccclass export default class Score extends cc.Component { private _score: number = 0; @property get score () { return this._score; } set score (value) { this._score = value; this.getComponent(cc.Label).string = this._score + ; } // 编辑框输入事件 public inputScore (string: string ,editbox: cc.EditBox) { let s = parseInt(string); this.score = s; } }
实现效果:双向绑定
结语
使用 get/set 的好处
-
灵活控制读写权限 为抽象做准备 数据可靠性 可以实现 MVVM
O(∩_∩)O~~