freeCodeCamp/guide/chinese/certifications/javascript-algorithms-and-d.../object-oriented-programming/use-closure-to-protect-prop.../index.md

640 B

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

使用闭包保护对象内的属性不被外部修改

方法

就像在给出的示例中一样,不是使用this关键字声明weight变量,而是必须使用let关键字将其声明为私有变量。这样它只能在Bird函数内访问。然后必须在Bird函数内添加getWeight方法以访问weight变量。

function Bird() { 
  let weight = 15; 
 
  this.getWeight = function() { 
    return weight; 
  }; 
 
 }