Arrow functions in ES2015 provide a more concise syntax.
Can I replace all my function declarations / expressions with arrow functions now?
What do I have to look out for?
Examples:
Constructor function
function User(name) {
this.name = name;
}
// vs
const User = name => {
this.name = name;
};
Prototype methods
User.prototype.getName = function() {
return this.name;
};
// vs
User.prototype.getName = () => this.name;
Object (literal) methods
const obj = {
getName: function() {
// ...
}
};
// vs
const obj = {
getName: () => {
// ...
}
};
Callbacks
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, 500);
Variadic functions
function sum() {
let args = [].slice.call(arguments);
// ...
}
// vs
const sum = (...args) => {
// ...
};
tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.
As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:
1. Lexical this and arguments
Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):
// Example using a function expression
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: function() {
console.log('Inside `bar`:', this.foo);
},
};
}
createObject.call({foo: 21}).bar(); // override `this` inside createObject
// Example using a arrow function
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: () => console.log('Inside `bar`:', this.foo),
};
}
createObject.call({foo: 21}).bar(); // override `this` inside createObject
In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.
This makes arrow functions useful if you need to access the this of the current environment:
// currently common pattern
var that = this;
getData(function(data) {
that.data = data;
});
// better alternative with arrow functions
getData(data => {
this.data = data;
});
Note that this also means that is not possible to set an arrow function's this with .bind or .call.
If you are not very familiar with this, consider reading
MDN - this
YDKJS - this & Object prototypes
2. Arrow functions cannot be called with new
ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).
Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable.
class constructors are only constructable.
If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.
Knowing this, we can state the following.
Replaceable:
Functions that don't use this or arguments.
Functions that are used with .bind(this)
Not replaceable:
Constructor functions
Function / methods added to a prototype (because they usually use this)
Variadic functions (if they use arguments (see below))
Generator functions, which require the function* notation
Lets have a closer look at this using your examples:
Constructor function
This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.
Prototype methods
Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
Object methods
Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:
const obj = {
getName() {
// ...
},
};
Callbacks
It depends. You should definitely replace it if you are aliasing the outer this or are using .bind(this):
// old
setTimeout(function() {
// ...
}.bind(this), 500);
// new
setTimeout(() => {
// ...
}, 500);
But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!
Variadic functions
Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.
// old
function sum() {
let args = [].slice.call(arguments);
// ...
}
// new
const sum = (...args) => {
// ...
};
Related question:
When should I use arrow functions in ECMAScript 6?
Do ES6 arrow functions have their own arguments or not?
What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?
How to use arrow functions (public class fields) as class methods?
Further resources:
MDN - Arrow functions
YDKJS - Arrow functions
Arrow functions => best ES6 feature so far. They are a tremendously
powerful addition to ES6, that I use constantly.
Wait, you can't use arrow function everywhere in your code, its not going to work in all cases like this where arrow functions are not usable. Without a doubt, the arrow function is a great addition it brings code simplicity.
But you can’t use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.
Arrow functions should NOT be used because:
They do not have this
It uses “lexical scoping” to figure out what the value of “this”
should be. In simple word lexical scoping it uses “this” from the
inside the function’s body.
They do not have arguments
Arrow functions don’t have an arguments object. But the same
functionality can be achieved using rest parameters.
let sum = (...args) => args.reduce((x, y) => x + y, 0);
sum(3, 3, 1) // output: 7
They cannot be used with new
Arrow functions can't be constructors because they do not have a prototype property.
When to use arrow function and when not:
Don't use to add function as a property in object literal because we
can not access this.
Function expressions are best for object methods. Arrow functions
are best for callbacks or methods like map, reduce, or forEach.
Use function declarations for functions you’d call by name (because
they’re hoisted).
Use arrow functions for callbacks (because they tend to be terser).
To use arrow functions with function.prototype.call, I made a helper function on the object prototype:
// Using
// #func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
They are not always equivalent. Here's a case where you cannot simply use arrow functions instead of regular functions.
Arrow functions CANNOT be used as constructors
TLDR:
This is because of how Arrow Functions use the this keyword. JS will simply throw an error if it sees an arrow function being invoked as a "constructor". Use regular functions to fix the error.
Longer explanation:
This is because objects "constructors" rely on the this keyword to be able to be modified.
Generally, the this keyword always references the global object. (In the browser it is the window object).
BUT, when you do something like:
function personCreator(name) {
this.name = name;
}
const person1 = new personCreator('John');
The new keyword do some of its magic and makes the this keyword that is inside of personCreator to be initially an empty object instead of referencing the global object. After that, a new property called name is created inside that empty this object, and its value will be 'John'. At the end, the this object is returned.
As we see, the new keyword changed the value of this from referencing the global object to now be an empty object {}.
Arrow functions do not allow their this object to be modified. Their this object is always the one from the scope where they were statically created. This is called Static Lexical Scope. That is why you cannot do operations like bind, apply, or call with arrow functions. Simply, their this is locked to the value of the this of the scope were they were created. This is by design.
And because of this :D, arrow functions cannot be used as "constructors".
Side Note:
A lexical scope is just the area where a function is created. For example:
function personCreator(name) {
this.name = name;
const foo = () => {
const bar = () => {
console.log(this); // Output: { name: 'John' }
}
console.log(this); // Output: { name: 'John' }
bar();
}
foo();
}
const person1 = new personCreator('John');
The lexical scope of bar is everything that is within foo. So, the this value of bar is the one that foo has, which is the one of personCreator.
I have added to the String class three prototype classes on a file classed parse.js:
String.prototype.parseCropTo = function (needle) {
if (this.includes(needle) === false) return false;
return this.slice(0, this.indexOf(needle)).trim();
}
String.prototype.parseCropFrom = function (needle) {
if (this.includes(needle) === false) return false;
return this.slice(this.indexOf(needle) + needle.length).trim();
}
String.prototype.parseCropBetween = function (needleFrom, needleTo) {
let haystack = this.parseCropFrom(needleFrom);
if (haystack != false) return haystack.parseCropTo(needleTo);
}
As far as I can see, imported files have to expose specific functions and then they are called via a variable. However, I wish to import parse.js to other files so I could use these functions directly on strings:
let haystack = 'This is a lovely day';
console.log(haystack.parseCropBetween('is', 'day'));
Is this possible? thanks in advance.
By extending the prototype of String, you will have these methods on every string you'll ever use, however you need to load it somewhere in your code, because you won't be able to use that beforehand.
The reason that works is because your'e accessing String.prototype by reference, as with all non-primitive types in javascript so calling it once, will get you set for the rest of your code.
Generally speaking, it's not advised to extend native constructs.
See full example here:
https://codesandbox.io/s/epic-cerf-4qshv?file=/src/App.js
Additionally, I'd advise you to read some opinions about extending prototypes in javascript and considers the pros and cons of this approach:
Why is extending native objects a bad practice?
How do we use 'inheritance' in Node.JS? I heard that prototype is similar to interfaces in java. But I have no idea how to use it!
Although there are various ways of performing inheritance and OO in javascript, in Node.js you would typically use the built in util.inherits function to create a constructor which inherits from another.
See http://book.mixu.net/ch6.html for a good discussion on this subject.
for example:
var util = require("util");
var events = require("events");
function MyOwnClass() {
// ... your code.
}
util.inherits(MyOwnClass, events.EventEmitter);
Creating an object constructor in pure JS:
They're just functions like any other JS function but invoked with the new keyword.
function Constructor(){ //constructors are typically capitalized
this.public = function(){ alert(private); }
var private = "Untouchable outside of this func scope.";
}
Constructor.static = function(){ alert('Callable as "Constructor.static()"'); }
var instance = new Constructor();
Inheritance:
function SubConstructor(){
this.anotherMethod(){ alert('nothing special'); }
}
function SubConstructor.prototype = new Constructor();
var instance = new SubConstructor();
instance.public(); //alerts that private string
The key difference is that prototypal inheritance comes from objects, rather than the things that build them.
One disadvantage is that there's no pretty way to write something that makes inheritance of instance vars like private possible.
The whopping gigantor mega-advantage, however, is that we can mess with the prototype without impacting the super constructor, changing a method or property for every object even after they've been built. This is rarely done in practice in higher-level code since it would make for an awfully confusing API but it can be handy for under-the-hood type stuff where you might want to share a changing value across a set of instances without just making it global.
The reason we get this post-instantiated behavior is because JS inheritance actually operates on a lookup process where any method call runs up the chain of instances and their constructor prototype properties until it finds the method called or quits. This can actually get slow if you go absolutely insane with cascading inheritance (which is widely regarded as an anti-pattern anyway).
I don't actually hit prototype specifically for inheritacne a lot myself, instead preferring to build up objects via a more composited approach but it's very handy when you need it and offers a lot of less obvious utility. For instance when you have an object that would be useful to you if only one property were different, but you don't want to touch the original.
var originInstance = {
originValue:'only on origin',
theOneProperty:'that would make this old object useful if it were different'
}
function Pseudoclone(){
this.theOneProperty = "which is now this value";
}
Pseudoclone.prototype = originInstance;
var newInstance = new Psuedoclone();
//accesses originInstance.originValue but its own theOneProperty
There are more modern convenience methods like Object.create but only function constructors give you the option to encapsulate private/instance vars so I tend to favor them since 9 times out of 10 anything not requiring encapsulation will just be an object literal anyway.
Overriding and Call Object Order:
( function Constructor(){
var private = "public referencing private";
this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
instance.myMethod = function(){ alert(private); }
instance.myMethod();//"undefined"
Note: the parens around the constructor allow it to be defined and evaluated in one spot so I could treat it like an object on the same line.
myMethod is alerting "undefined" because an externally overwritten method is defined outside of the constructor's closure which is what effective makes internal vars private-like. So you can replace the method but you won't have access to what it did.
Now let's do some commenting.
( function Constructor(){
var private = "public referencing private";
this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
//instance.myMethod = function(){ alert(private); }
instance.myMethod();//"public referencing private"
and...
( function Constructor(){
var private = "public referencing private";
//this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
//instance.myMethod = function(){ alert(private); }
instance.myMethod();//"prototype"
Note that prototype methods also don't have access to that internal private var for the same reason. It's all about whether something was defined in the constructor itself. Note that params passed to the constructor will also effectively be private instance vars which can be handy for doing things like overriding a set of default options.
Couple More Details
It's actually not necessary to use parens when invoking with new unless you have required parameters but I tend to leave them in out of habit (it works to think of them as functions that fire and then leave an object representing the scope of that firing behind) and figured it would be less alien to a Java dev than new Constructor;
Also, with any constructor that requires params, I like to add default values internally with something like:
var param = param || '';
That way you can pass the constructor into convenience methods like Node's util.inherit without undefined values breaking things for you.
Params are also effectively private persistent instance vars just like any var defined in a constructor.
Oh and object literals (objects defined with { key:'value' }) are probably best thought of as roughly equivalent to this:
var instance = new Object();
instance.key = 'value';
With a little help from Coffeescript, we can achieve it much easier.
For e.g.: to extend a class:
class Animal
constructor: (#name) ->
alive: ->
false
class Parrot extends Animal
constructor: ->
super("Parrot")
dead: ->
not #alive()
Static property:
class Animal
#find: (name) ->
Animal.find("Parrot")
Instance property:
class Animal
price: 5
sell: (customer) ->
animal = new Animal
animal.sell(new Customer)
I just take the sample code Classes in CoffeeScript. You can learn more about CoffeeScript at its official site: http://coffeescript.org/
I have a requirement to extend the YUI Panel with some custom functionality that will be in a new file and shared across multiple views.
I am at a bit of a loss as to how best to go about this, can anyone give me any pointers please?
Let's say you want to extend a Panel to create one that has a list in its body. I usually use Y.Base.create for this. It's a more declarative way of extending YUI classes than using a constructor and Y.extend. But I'll stay closer to your example in the YUI forums.
There are a couple of tricks dealing with WidgetStdMod (one of the components of Y.Panel), but mostly it's just about using Y.extend and following the YUI inheritance patterns. I'll try to answer with an example:
function MyPanel() {
MyPanel.superclass.constructor.apply(this, arguments);
}
// hack: call it the same so you get the same css class names
// this is good for demos and tests. probably not for real life
MyPanel.NAME = 'panel';
MyPanel.ATTRS = {
listItems: {
// YUI now clones this array, so all's right with the world
value: []
},
bodyContent: {
// we want this so that WidgetStdMod creates the body node
// and we can insert our list inside it
value: ''
}
};
Y.extend(MyPanel, Y.Panel, {
// always a nice idea to keep templates in the prototype
LIST_TEMPLATE: '<ul class="yui3-panel-list"></ul>',
initializer: function (config) {
// you'll probably want to use progressive enhancement here
this._listContainer = Y.Node.create(this.LIST_TEMPLATE);
// initializer is also the place where you'll want to instantiate other
// objects that will live inside the panel
},
renderUI: function () {
// you're inheriting from Panel, so you'll want to keep its rendering logic
// renderUI/bindUI/syncUI don't call the superclass automatically like
// initializer and destructor
MyPanel.superclass.renderUI.call(this);
// Normally we would append stuff to the body in the renderUI method
// Unfortunately, as of 3.5.0 YUI still removes all content from the body
// during renderUI, so we either hack it or do everything in syncUI
// Hacking WidgetStdModNode is doable but I don't have the code around
// and I haven't memorized it
//var body = this.getStdModNode('body');
},
syncUI: function () {
// same here
MyPanel.superclass.syncUI.call(this);
// insert stuff in the body node
var listContainer = this._listContainer.appendTo(this.getStdModNode('body'));
Y.Array.each(this.get('listItems'), function (item) {
listContainer.append('<li>' + item + '</li>');
});
}
});
Still finding my feet with Haxe and am looking for way to have a array-like read-only collection that I can specify a type for at compile time
So ideally I need something like the following:
var collection:Collection<ItemType>;
var item:ItemType = collection[3];//or
var other:ItemType = collection.getAt(3);
//also, it would be good if it was iterable
for (item in collection)
{
//stuff
}
So, exactly like an Array, but read only. Would anybody be able to give me a few pointers, please.
Many thanks
Well, you can't have read-only array access as such, but you can do it with methods:
class ReadonlyArray<T> {
var source:Array<T>;
public function new(source) this.source = source
inline function get(index) return source[index]
inline function iterator() return index.iterator()
}
The overhead should be barely noticeable.