* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.3 KiB
2.3 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d7db2367417b2b2512b8a | 使用闭包保护对象内的属性不被外部修改 | 1 | 18234 | use-closure-to-protect-properties-within-an-object-from-being-modified-externally |
--description--
在上一次挑战中,bird
有一个公共属性name
。公共属性的定义就是:它可以在bird
的定义范围之外被访问和更改。
bird.name = "Duffy";
因此,代码的任何地方都可以轻松地将bird
的 name 属性更改为任意值。想想密码和银行账户之类的东西,如果代码库的任何部分都可以轻易改变,那么将会引起很多问题。
使属性私有化最简单的方法就是在构造函数中创建变量。可以将该变量范围限定在构造函数中,而不是全局可用。这样,属性只能由构造函数中的方法访问和更改。
function Bird() {
let hatchedEgg = 10; // 私有变量
/* bird 对象可用的公共方法 */
this.getHatchedEggCount = function() {
return hatchedEgg;
};
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // 返回 10
这里的getHachedEggCount
是一种特权方法,因为它可以访问私有属性hatchedEgg
。这是因为hatchedEgg
是在与getHachedEggCount
相同的上下文中声明的。在 JavaScript 中,函数总是可以访问创建它的上下文。这就叫做闭包
。
--instructions--
更改在Bird
函数中声明的weight
方法,使其成为私有变量。然后,创建一个返回weight
值的getWeight
方法。
--hints--
weight
属性应该是一个私有变量,值应该是 15
。
assert(code.match(/(var|let|const)\s+weight\s*\=\s*15\;?/g));
你的代码应该在Bird
中创建一个名为getWeight
方法,该方法返回weight
值。
assert(
new Bird().getWeight() === 15,
'你的代码应该在<code>Bird</code>中创建一个名为<code>getWeight</code>方法,该方法返回<code>weight</code>值。'
);
Your getWeight
function should return the private variable weight
.
assert(code.match(/((return\s+)|(\(\s*\)\s*\=\>\s*))weight\;?/g));
--seed--
--seed-contents--
function Bird() {
this.weight = 15;
}
--solutions--
function Bird() {
let weight = 15;
this.getWeight = () => weight;
}