ES6入门学习日记
JavaScript 闭包
偶然看到昨天没关的网页, 复习一下JS 闭包
//例子1
var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  alert(object.getNameFunc()()); //The Window
/*
阮一峰老师留的思考题.
即考察this和闭包
本题执行#15行语句的过程
alert(object.getNameFunc()());
=====>
alert(function(){return this.name;}());
/*
在任何函数体外部出现了this, 这时候this指向顶层对象window,而this.name即#1由var声明的name.
而由var声明的全局变量会同时成为顶层对象window的一个属性.
*/
*/
//例子2
var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };
    }
  };
  alert(object.getNameFunc()());
/*
阮一峰老师留的思考题.
即考察this和闭包
本题执行#15行语句的过程
alert(object.getNameFunc()());
=====>
alert(function(){return that.name;}());
/*
getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };
    }
   //
   这一段形成了闭包,所以在内存中that保存了this所指的object对象.
   所以当执行that.name时,当然是指object.name
*/
ES6
解构赋值
对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。
const { log } = console; //console是个对象, #1执行后,将console对象中的log()方法赋值给了log变量
log('hello') // hello
解构也可以用于嵌套结构的对象
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
//注意,这时p是模式,不是变量,因此不会被赋值。如果p也要作为变量赋值,可以写成下面这样。
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]
对象的解构赋值可以取到继承的属性
const obj1 = {};
const obj2 = { foo: 'bar' };
//Object.setPrototypeOf(obj, prototype) 设置prototype为obj的新原型
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
默认值
难点
块级作用域与函数声明
疑问
…tail 写法
let [head, ...tail] = [1, 2, 3, 4]; //这...tail是个啥= =#
head // 1
tail // [2, 3, 4]
Generator 函数
function* fibs() {
let a = 0;
let b = 1;
//下面这块没看懂
while (true) {
yield a;
[a, b] = [b, a + b];
}
//
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5