freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/use-closure-to-protect-prop...

2.6 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7db2367417b2b2512b8a Use Closure to Protect Properties Within an Object from Being Modified Externally 1 使用闭包保护对象内的属性不被外部修改

Description

在之前的挑战中, bird有一个公共财产name 。它被认为是公开的,因为它可以在bird的定义之外进行访问和更改。
bird.name =“达菲”;
因此,代码的任何部分都可以轻松地将bird的名称更改为任何值。考虑一下代码库的任何部分都可以轻松更改密码和银行帐户等内容。这可能会导致很多问题。使属性私有的最简单方法是在构造函数中创建一个变量。这会将该变量的范围更改为构造函数,而不是全局可用。这样,只能通过构造函数中的方法访问和更改属性。
function Bird{
让hatchedEgg = 10; // 私人财产

this.getHatchedEggCount = function{//鸟类对象可以使用的公共可用方法
返回hatchedEgg;
};
}
让ducky = new Bird;
ducky.getHatchedEggCount; //返回10
这里getHachedEggCount是一种特权方法,因为它可以访问私有变量hatchedEgg 。这是可能的,因为hatchedEgg在与getHachedEggCount相同的上下文中getHachedEggCount 。在JavaScript中函数始终可以访问创建它的上下文。这叫做closure

Instructions

更改Bird函数中声明weight方式,使其成为私有变量。然后,创建一个返回weight值的方法getWeight

Tests

tests:
  - text: <code>weight</code>属性应该是私有变量。
    testString: 'assert(!code.match(/this\.weight/g), "The <code>weight</code> property should be a private variable.");'
  - text: 你的代码应该在<code>Bird</code>创建一个名为<code>getWeight</code>的方法来返回<code>weight</code> 。
    testString: 'assert((new Bird()).getWeight() === 15, "Your code should create a method in <code>Bird</code> called <code>getWeight</code> that returns the <code>weight</code>.");'

Challenge Seed

function Bird() {
  this.weight = 15;


}

Solution

// solution required