Study Notes

Study Notes

  • Source
  • WebDesign
  • Javascript

›Object Oriented Programming

Basic Javascript

  • Basic JavaScript Overview

ES6

  • ES6 Overview

Regular expression

  • Regular Expression Overview
  • Lookahead
  • Capture Group

Debugging

  • Debugging Overview

Object Oriented Programming

  • Object Oriented Programming Overview
  • Mixin
  • Closure
  • IIFE

Functional Programming

  • Functional Programming

Basic Algorithm Script

  • Reverse a String
  • Factorialize a Number
  • Find the Longest Word in a String
  • Return Largest Numbers In Arrays
  • Repeat a String
  • Truncate a String
  • Finders Keepers
  • Boo Who
  • Title Case a Sentence
  • Slice and Splice
  • Falsy Bouncer
  • javascript-algorithms-anddata-structures/basic-algorithm-scripting/where-do-i-belong
  • Mutations
  • Chunky Monkey

Intermediate Algorithm Script

  • Sum All Numbers in a Range
  • Diff Two Arrays
  • Seek and Destroy
  • Wherefor Art Thou
  • Spinal Tap Case
  • Search and Replace
  • DNA Pairing
  • Missing letters
  • Sorted Union
  • Convert HTML Entities
  • Sum All Odd Fibonacci Numbers
  • Smallest Common Multiple
  • Drop it
  • Steamroller
  • Binary Agents
  • Everything Be True
  • Arguments Optional
  • Make a Person
  • Map the Debris

Closure

Closure 的定义:

In JavaScript, a function always has access to the context in which it was created. This is called closure.

Closure 也就是我们所说的闭包。

在 Use Closure to Protect Properties Within an Object from Being Modified Externally 这个练习中,介绍了如何利用 Closure 去实现对象的属性不被外部所修改。

一般在构造函数中,会像下面的例子那样去声明。实例化的对象的属性,能够在外部直接被修改。

function People(name) {
  this.name = name;
  this.sayHi = function() {
    console.log(`My name is ${this.name}.`)
  }
}

const foo = new People('foo');
foo.sayHi(); // My name is foo.
foo.name = 'bar';
foo.sayHi(); // My name is bar.

如果希望实例化的对象的属性不被外部直接修改,可以像下面的例子将对象的属性声明为构造函数的内部属性。属性的获取和修改都只能通过构造函数中定义的接口去获取和修改。

function People(initialName) {
  let name = initialName;
  this.sayHi = function() {
    console.log(`My name is ${name}.`);
  }
  this.setName = function(newName) {
    name = newName;
  }
}

const foo = new People('foo');
foo.sayHi(); // My name is foo.
foo.setName('bar');
foo.sayHi(); // My name is bar.

再回顾一下联系中,对 Closure 的定义:

In JavaScript, a function always has access to the context in which it was created. This is called closure.

第二种构造函数的声明,就是巧妙地利用了闭包的特性,实现了对象不被外部直接修改的要求。

参考资料:

  • FreeCodeCamp: Use Closure to Protect Properties Within an Object from Being Modified Externally
← MixinIIFE →
Copyright © 2019 罗惠东