码迷,mamicode.com
首页 > 其他好文 > 详细

ES6 new syntax of Arrow Function

时间:2018-04-16 21:09:17      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:cto   order   creat   let   turned   example   ted   john   info   

Arrow Function.md

Arrow Functions

The basic syntax of an arrow function is as follows

var fn = data => data;

The code means :

var fn = function( data ) {
    return data;
}
let getNumber = () => 42;

console.log(typeof getNumber);
console.log(getNumber());
var getPrice = (quantity,tax) => (quantity * 5) + (1 + tax);
console.log(getPrice(2,.095));
var getPrice = (quantity,tax) => {
    let price = (quantity * 5)
    price *= (1 + tax);
    return price;
}
console.log(getPrice(2,.095));
var getNumber = data => ({data: ‘check‘, number: 42});
var getNumber = function(data) {
    return {
        data:‘check‘,
        number: 42
    }
}

How create IIFEs using arrow function?

var fn = function( number) {
    return {
        getNumber: function(){
            return number;
        }
    }
}(42);

console.log(fn.getNumber);

Why we use IIFEs?

This is an effective pattern to shield the expression from the rest of program.

var fn = ((number) => {
    return {
        getNumber: function() {
            return number;
        } 
    }
})(42);
console.log(fn.getNumber());

Difference of function expressions and function declarations
Arrow function do save us a few lines of code and characters ,but the real purpose of the arrow funcion is to handlethe this keyword within functions. this behaves differently inside an arrow function.

Let‘s take a look at how the this keyword work in general

A tale about this
1.Function Invocation

function getContext(){
    console.log(this);
}

getContext() is a Window/Global object.At the time getContext() is called,JavaScript automatically sets this at the global object,which in browser is Window.

if(this === window){
    console.log(‘This refers to the global context‘)
}

2.Method Invocation

let myObj = {
    name: ‘fancy‘,
    opration: function(){
        console.log(this)
    }
}
myObj.opration();
let x = myObj.opration;
x();
let x =  myObj.opration;
x();
x.call(myObj);
//myObj.x()?

3.Construtor Invocation

what is constructor invocation?

Constructor invocation happens when an object is created using the new keyword.

function Employee( name, department, salary){
    this.name = name;
    this.department = department;
    this.salary = salary;

    console.log(‘Welcome‘+this.name+"!");
}

let john = new Employee(‘Johe‘, ‘Sales‘, 4000 ); 

this in arrow funcion

Arrow function are designed to lexically bind the
context ,which means that this refers to the enclosing
context where the arrow funcion is defined.Unlike a
normal function, arrow function does not create its
own excution context,but takes this from outer function
where it is defined.

function Employee(firstName, department, salary){
    this.firstName = firstName;
    this.department = department;
    this.salary = salary;

    this.getInfo = function(){
        return function(){
            console.log(this.firstName + " from " +
            this.department + " earns " + this.salary
            );
        }
    }
}

let jim = new Employee(‘Jim‘, ‘Finance‘, ‘5200‘);
let printInfo = jim.getInfo();
printInfo();

In this section, Employee is a construtor function and
we created a new employee object called jim using the
constructor function with the new keyword.In order to
print the employee information,we need using the function
returned by jim.getInfo().

Here,printInfo refers to the inner function and since
we are simply making a function invocation,this refers to
the Global object that does not have any Employee properties
and hence produces undefined whenever a property on this is
used.

In the section,we replace the inner function with an arrow function.

In this case,the this keyword refers to the context of the function
enclosing the arrow function unlike the previous case where it referred
the Global object.At the point,it is important to note that arrow functions
do not change their context on invocation.

function Employee(firstName, department, salary) {
    this.firstName = firstName;
    this.department = department;
    this.salary = salary;

    this.getInfo = function(){
        return() => {
            console.log(this.firstName + " from " +
             this.department + " earns " + this.salary);
        };
    }
}

let jim = new Employee (‘Jim‘, ‘Finance‘, 5200);

let printInfo = jim.getInfo();
printInfo();
function Employee(){
    this.firstName = "Jack",
    this.department = "HR",
    this.salary = 4500,

    this.getContext = () => {
        console.log(this);
    }

    let mark = new Employee();
    mark.getContext();

    let context = mark.getContext;
    context();
}

In the above example,the context of the arrow function was set
on declaration and it cannot be changed.An important thing to note
here is that you cannot "rebind" an arrow funtion.The context
always fixed.

var details = {
    number: 42,
    opration: function(){
        return () => console.log(this.number);
    }
};

var details = {
    number: 84
};

details.opration().bind(details2)();

In the example,we are setting the details2 number to 84.But we
now we can‘t bind a new object to arrow function.The engine does
not throw any error,it just ingores the bind completely. So
42 is printed even if we call the opration method with the details2
object.This also applies to call and apply.So with an arrow function,
calls to bind,call or apply will not be able to change to value
of this.

var product = ( x, y ) => x * y;
console.log(product.call(null,2,3));
console.log(product.apply(null, [2,3]));

var multiply = product.bind(null, 2, 3);
console.log(multiply());
var newFn = () => { },
    object = new newFn();
var details = () => 42;
console.log(details.hasOwnProperty("prototype"));

Using arrow function

So,whenever you have a short single-statement inline function
expression,with a computed return value and the function does not
make a reference a self-reference,you can replace it with an
arrow function.

$(‘.btn‘).on(‘click‘, function(){
    var self = this;

    setTimeout({
        $(self).toggleClass(‘btn-active‘);
        },1000);
    });
$(‘.btn‘).on(‘click‘,function(){
    setTimeout(() => {
        $(this).toggleClass(‘btn-active‘);
        },1000);
    });

ES6 new syntax of Arrow Function

标签:cto   order   creat   let   turned   example   ted   john   info   

原文地址:https://www.cnblogs.com/InnerPeace-Hecdi/p/8858464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!