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
。 Bird
函数中声明weight
方式,使其成为私有变量。然后,创建一个返回weight
值的方法getWeight
。 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
.");'
```