Scope, closures, prototype

1. Scope

1) global scope
2) Function scope
3) block-level scope

// 最顶层作用域即为全局作用域 
function test() {
  if (true) {
    var a = 1
    let b = 2
  }
  console.log('a: ', a);  // 在函数里用var声明的变量都是局部变量
  console.log('b: ', b);  // 使用let声明的变量只在定义的代码块内有效
}

test()

Summary: The scope is the mechanism js variable access.

2. Closure

Outside a function to access the variables within function
1)

var a = function outer() {
  var a = 2
  return function () {
    a ++
    return a
  }
}
var b = a()
b() // 3
b() // 4

2) the role and drawbacks
role:
to achieve private variables, global variables reduce
disadvantages:
cost of memory, memory leaks easily lead

3. Prototype

Each function has a prototype object property, pointing to another object
for all properties and methods of prototype (object properties), will be inherited instance constructor
prototype is to call prototype (proto) of that instance of the object created by the constructor.


function Animal(animal) { 
  this.name = animal
}
Animal.prototype.getName = function() {
  return this.name
}
Animal.prototype.setName = function(name) {
  this.name = name
}
 // Animal 的prototype.constructor关联到Animal本身
console.log('Animal 的prototype.constructor关联到Animal本身: ',  Animal === Animal.prototype.constructor)
 // Animal  就是构造函数   a就是实例对象  
 // 每次创建对象的时候就将该对象的__proto__属性关联到构造函数的prototype属性
var a = new Animal('dog')
console.log(a)
console.log(a.getName())
console.log(a.__proto__ === Animal.prototype)

Guess you like

Origin www.cnblogs.com/coldfrost/p/11729272.html