--- id: 587d7db2367417b2b2512b8a title: Use Closure to Protect Properties Within an Object from Being Modified Externally challengeType: 1 videoUrl: '' localeTitle: 使用闭包保护对象内的属性不被外部修改 --- ## 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
```yml tests: - text: weight属性应该是私有变量。 testString: 'assert(!code.match(/this\.weight/g), "The weight property should be a private variable.");' - text: 你的代码应该在Bird创建一个名为getWeight的方法来返回weight 。 testString: 'assert((new Bird()).getWeight() === 15, "Your code should create a method in Bird called getWeight that returns the weight.");' ```
## Challenge Seed
```js function Bird() { this.weight = 15; } ```
## Solution
```js // solution required ```