阿新

ES6与ES3,5的区别(一)
ES6与ES3,5的区别(一)const区别// ES5 中常量的写法 Object.defineProperty...
扫描右侧二维码阅读全文
21
2018/06

ES6与ES3,5的区别(一)

ES6与ES3,5的区别(一)


const区别

// ES5 中常量的写法
Object.defineProperty(window, "PI2", {
    value: 3.1415926,
    writable: false,
})
console.log(window.PI2)

// ES6 的常量写法
const PI = 3.1415926
console.log(PI)
// PI = 4

作用域

// ES5 中作用域
const callbacks = []
for (var i = 0; i <= 2; i++) {
    callbacks[i] = function() {
        return i * 2
    }
}

//输出6,6,6
console.table([
    callbacks[0](),
    callbacks[1](),
    callbacks[2](),
]) 

const callbacks2 = []
for (let j = 0; j <= 2; j++) {
    callbacks2[j] = function() {
        return j * 2
    }
}

//输出0,2,4
console.table([
    callbacks2[0](),
    callbacks2[1](),
    callbacks2[2](),
])

//ES5采用执行function方式隔离作用域
;((function() {
    const foo = function() {
        return 1
    }
    console.log("foo()===1", foo() === 1)//true
    ;((function() {
        const foo = function() {
            return 2
        }
        console.log("foo()===2", foo() === 2)//true
    })())
})())

//ES6直接用{}隔离
{
    function foo() {
        return 1
    }
    console.log("foo()===1", foo() === 1)//true
    {
        function foo() {
            return 2
        }
        console.log("foo()===2", foo() === 2)//true
    }
    console.log("foo()===1", foo() === 1)//true
}

箭头函数的定义


{
  // ES3,ES5
  var evens = [1, 2, 3, 4, 5];
  var odds = evens.map(function(v) {
    return v + 1
  });
  console.log(evens, odds);
};
{
  // ES6
  let evens = [1, 2, 3, 4, 5];
  //一个参数的时候,()可以省略,表达式作为返回的时候,{}可以省略
  let odds = evens.map(v => v + 1);
  console.log(evens, odds);
} {
  // ES3,ES5
  var factory = function() {
    this.a = 'a';
    this.b = 'b';
    this.c = {
      a: 'a+',
      b: function() {
      //谁调用,指向谁,这个this指向c
        return this.a
      }
    }
  }
  console.log(new factory().c.b());//a+
};

{
  var factory = function() {
    this.a = 'a';
    this.b = 'b';
    this.c = {
      a: 'a+',
      b: () => {
      //这个this指向实例时的对象,这里是factory
        return this.a
      }
    }
  }
  console.log(new factory().c.b());//a
}
Last modification:August 13th, 2018 at 11:24 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment