阿里云主机折上折
  • 微信号
Current Site:Index > Extension methods for functions

Extension methods for functions

Author:Chuan Chen 阅读数:19356人阅读 分类: JavaScript

ECMAScript 6 introduced extensive enhancements to functions, including features such as arrow functions, parameter default values, rest parameters, the name property, and tail call optimization. These improvements make functions more flexible and concise while enhancing code readability and performance.

Arrow Functions

Arrow functions are a new function syntax introduced in ES6, defined using =>. They simplify function syntax and do not bind their own this; instead, they inherit the this value from the enclosing scope.

// Traditional function
const add = function(a, b) {
  return a + b;
};

// Arrow function
const add = (a, b) => a + b;

Arrow functions are particularly useful for callback functions, such as in array methods:

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]

Note that arrow functions do not have their own arguments object and cannot be used as constructors:

const foo = () => {
  console.log(arguments); // Error: arguments is not defined
};

new foo(); // Error: foo is not a constructor

Default Parameter Values

ES6 allows setting default values for function parameters. The default value is used when the parameter is undefined.

function greet(name = 'Guest') {
  console.log(`Hello, ${name}!`);
}

greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!

Default values can be expressions or even function calls:

function getDefault() {
  return 'Default Value';
}

function foo(value = getDefault()) {
  console.log(value);
}

foo(); // Default Value

Rest Parameters

The rest parameter syntax allows representing an indefinite number of arguments as an array, replacing the traditional arguments object.

function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15

The rest parameter must be the last parameter:

function foo(a, ...rest, b) { // Syntax error
  // ...
}

The name Property of Functions

ES6 adds a name property to functions, allowing you to retrieve the function's name.

function foo() {}
console.log(foo.name); // "foo"

const bar = function() {};
console.log(bar.name); // "bar"

const baz = () => {};
console.log(baz.name); // "baz"

For anonymous functions assigned to variables, the name property returns the variable name:

const anonymous = function() {};
console.log(anonymous.name); // "anonymous"

Tail Call Optimization

Tail Call Optimization (TCO) is a significant optimization in ES6. When the last step of a function is to call another function, the engine can reuse the current call stack instead of creating a new one.

function factorial(n, total = 1) {
  if (n === 1) return total;
  return factorial(n - 1, n * total); // Tail call
}

console.log(factorial(5)); // 120

Note that tail call optimization is only enabled in strict mode:

'use strict';

function foo() {
  return bar(); // Tail call optimization
}

Destructuring Assignment in Function Parameters

ES6 allows destructuring assignment in function parameters, enabling direct extraction of values from parameters.

function foo({x, y}) {
  console.log(x, y);
}

foo({x: 1, y: 2}); // 1 2

function bar([a, b]) {
  console.log(a, b);
}

bar([10, 20]); // 10 20

This can be combined with default values:

function draw({size = 'big', coords = {x: 0, y: 0}} = {}) {
  console.log(size, coords.x, coords.y);
}

draw(); // big 0 0

The Double Colon Operator

The double colon operator :: was a proposed feature in ES6 for binding function context. Although it was not included in the final standard, understanding it helps with function binding concepts.

const obj = {
  value: 42,
  getValue() {
    return this.value;
  }
};

const unboundGetValue = obj.getValue;
console.log(unboundGetValue()); // undefined

const boundGetValue = ::obj.getValue;
console.log(boundGetValue()); // 42

Trailing Commas in Function Parameters

ES6 allows trailing commas in function parameter lists, which is particularly useful for multiline parameter lists.

function foo(
  param1,
  param2, // Trailing comma allowed
) {
  // ...
}

new.target

The new.target property is used to detect whether a function was called with new, which is especially useful in constructors.

function Foo() {
  if (!new.target) {
    throw new Error('Must be called with new');
  }
  console.log('Foo called with new');
}

new Foo(); // Foo called with new
Foo(); // Error: Must be called with new

Block-Scoped Functions

In ES6, function declarations are block-scoped, unlike the hoisting behavior in ES5.

{
  function foo() { console.log('inside'); }
  foo(); // inside
}

foo(); // Error: foo is not defined

Generator Functions

Although generator functions are a separate topic, they are also part of ES6's function enhancements.

function* idMaker() {
  let index = 0;
  while (true) {
    yield index++;
  }
}

const gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:数值的扩展方法

下一篇:Math对象的扩展

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.