javascript ES5到ES6

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript ES5到ES6相关的知识,希望对你有一定的参考价值。

/**
 * Array in ES5/ES6
******************************************************/
const boxes = document.querySelectorAll('.box')

// ES5
  var boxesArr5 = Array.prototype.slice.call(boxes)
  boxesArr5.forEach(function(element) {
      console.log('ES5')
      return element.style.backgroundColor = 'dodgerblue'
  }, this);


// ES6
  var boxesArr6 = Array.from(boxes)
  boxesArr6.forEach(element => element.style.backgroundColor = 'dodgerblue')
  console.log('ES6')
  console.log(boxesArr6)



// ES5
  for (var i = 0; i < boxes.length; i++) {
      var element = boxes[i];
      if (element.className === 'box blue') {
          console.log(element)
          break
      }
      element.textContent = 'I\'ve changed!'
  }

// ES6
  for (const x of boxes) {
      if (x.className.includes('blue')) {
          x.textContent = 'I\'ve changed!'
          break
      }
  }


// ES5
var ages = [2, 1, 3, 35, 45, 30, 36, 42, 55]
var full = ages.map(function(element) {
    return element >= 36
});
console.log(full)

// ES6
var full = ages.find(element => element >= 3)
console.log(full)




/* ES5 - Classes
******************************************************/
var Person5 = function(name, yearOfBirth, job){
    this.name = name
    this.yearOfBirth = yearOfBirth
    this.job = job
  }
  Person5.prototype.calculateAge = function(){
    var age = (new Date().getFullYear() - this.yearOfBirth)
    console.log(age)
  }
  var person5 = new Person5('Joe', 1986, 'Front end developer')

// ES5 - Inheritance
  var Athelete5 = function(name, yearOfBirth, job, olymicGame, medals){
    // this keyword will point to an empty object
    //call method, this will be invoked only when we create an instance of Athlete5 such as in my line of code above. The Athlete5 function constructor will run, and the first thing it does is call the Person5 function constructor with the ‘this’ keyword set to our newly created Athlete5 object, which we have called john .
    Person5.call(this, name, yearOfBirth, job)
    this.olymicGame = olymicGame;
    this.medals = medals;
  }

  // Object.create allows you to manually set the prototype of an object.
  // In this case you want a prototype of Athelete5 to be a prototype of Person5 so this they will become connected
  Athelete5.prototype = Object.create(Person5.prototype)

  Athelete5.prototype.wonMedal = function(){
    this.medals ++
    console.log(this.medals);
  }

  var johnAthelete5 = new Athelete5('Joe', 1986, 'Web Developer', 5, 8)
      johnAthelete5.calculateAge()
      johnAthelete5.wonMedal()


/* ES6 - Classes
******************************************************/
  class Person6{
    constructor(name, yearOfBirth, job){
      this.name = name
      this.yearOfBirth = yearOfBirth
      this.job = job
    }
    calculateAge(){
      let age = (new Date().getFullYear() - this.yearOfBirth)
      console.log(age)
    }

    // static functionsta - usually use this as a helper function
    static greeting(){
    console.log('Hey, There!')
  }
}
  let person6 = new Person6('Joe', 1986, 'Front end developer')

  // callin static function
  Person6.greeting()

  class Athelete6 extends Person6{
    // With function constructors, you will need to repeat Person6 properties if you want them on johnAthelete6
    constructor(name, yearOfBirth, job, olymicGame, medals){
      super(name, yearOfBirth, job) //these are the constructors of Person6 class
      this.olymicGame = olymicGame
      this.medals = medals
    }

    wonMedal(){
      this.medals ++
      console.log(this.medals);
    }
  }

  const johnAthelete6 = new Athelete6('John', 1990, 'Swimmer', 5, 28)
      johnAthelete6.calculateAge()
      johnAthelete6.wonMedal()









/*=============================================
= Destructuring 
=============================================*/
// Array
  // ES5
  var joe = ['Joe', 31]
  var name = joe[0]
  var age = [1]
  console.log(name, age)

  // ES 6
  var joe = ["Joe", 31];
  const [name, age] =  joe

// Object
  const obj = {
    firstname: 'Joe',
    lastname: 'Boo'
  }
  const { firstname: first, lastname: last } = obj;

  function calcAgeRetirement(year){
    const age = new Date().getFullYear() - year
    return [age, 65 - age]
  }

  const [age, retirement] = calcAgeRetirement(1990)
  console.log(age)
  console.log(retirement)










// Example 1
function convertCurrency(amount) {
    const converted = {
      USD: amount * 0.76,
      GPB: amount * 0.53,
      AUD: amount * 1.01,
      MEX: amount * 13.30
    };
    return converted;
  }

  const hundo = convertCurrency(100)
  //  Destructuring an objects
  // you can put your objects in any order and it will works fine
  const { USD, GPB } = hundo
  // console.log(USD, GPB);


  // default name argument
  // when passing in as an objects, it's gonna Destructuring them into an object. This will Destructuring them into vaiable.
  function tipCalc({total = 100, tip = 0.15, tax = 0.13}) {
    return total + (tip * total) + (tax * total)
  }
  console.log(tipCalc({ tax: 0.3}))
  // const bill = tipCalc({ tip: 0.20, total: 200 });

  //Example 2
  const person = {
    first: 'Wes',
    last: 'Bos',
    country: 'Canada',
    city: 'Hamilton',
    twitter: '@wesbos'
  };

/*=============================================
=            Example 1                       =
=============================================*/
  // const first = person.first;
  // const last = person.last;
  // const twitter = person.twitter;
  // output: Object {first: "Wes", last: "Bos", country: "Canada", city: "Hamilton", twitter: "@wesbos"}
  const { first, last, country, city, twitter } = person;


/*=============================================
=            Example 2                        =
=============================================*/
  const wes = {
    first: 'Wes',
    last: 'Bos',
    links: {
      social: {
        twitter: 'https://twitter.com/wesbos',
        facebook: 'https://facebook.com/wesbos.developer',
      },
      web: {
        blog: 'https://wesbos.com'
      }
    }
  };
  // twitter is stored in 'tweet'
  // facebook is stored in 'fb'
  // console.log(tweet);
  // output: Object {twitter: "https://twitter.com/wesbos", facebook: "https://facebook.com/wesbos.developer"}
  const { twitter: tweet, facebook: facebook } = wes.links.social;


/*=============================================
=            Example 3                        =
=============================================*/
const settings = {
  // width: 300,
  color: 'black'
}  // require height, fontSize

const {
	width = 100,
	height = 100,
	color = 'blue',
	fontSize = 25
} = settings;
// output: Object {width: 300, color: "black"}

//Example 3
let inRing = 'Hulk Hogan';
  let onSide = 'The Rock';

  // console.log('in ring' + inRing, onSide);
  console.log('In ring:'+`${inRing} ` + ', On Side: ' + `${onSide}`);
  // result: In ring:Hulk Hogan , On Side: The Rock

  [inRing, onSide] = [onSide, inRing]; // switching string value

  // console.log(inRing, onSide);
  console.log('In ring:'+`${inRing} ` + ', On Side: ' + `${onSide}`);
	// result: In ring:The Rock , On Side: Hulk Hogan

// Example 4
// Ex.1
  const details = ['Joe Boo

以上是关于javascript ES5到ES6的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript ES5继承ES6 class继承

javascript ES5 / ES6技术

转换ES6中的ES5 IIFE,OOP Javascript编程

ES5与ES6的研究

javascript 从js数组中删除重复项(ES5 / ES6)

javascript 使用ES5 / ES6 Set()第1部分在Javascript中获取数组的唯一值