Secrets of the Javascript Ninja (Understanding functions)

it2023-07-21  73

函数

理解函数是揭秘JS语言的重要一环,你的JS编程水平大部分会取决于此。

Most important, in JavaScript, functions are first-class objects, or first-class citizens as they’re often called. They coexist with, and can be treated like, any other JavaScript object. Just like the moremundane JavaScript data types, they can be referenced by variables,declared with literals, and even passed as function parameters.

在JS中,函数是一等对象或者一等公民,你可以将其看作和对象一样,可以被当做变量一样引用,以字面量形式的声明,甚至可以被当做函数参数进行传递。 1、以字面量的形式创建,并可以为其分配属性

function ninjaFunction() {} ninja.data = function(){}; ninjaFunction.name = "Hanzo";

2、当做函数参数被传递

function call(ninjaFunction){ ninjaFunction(); } call(function(){});

3、被当做结果返回

function returnNewNinjaFunction() { return function(){}; }

一、回调函数

Callbacks are an essential part of using JavaScript effectively

回调函数作为JS函数的重要一环,鼠标响应回调事件,以及排序函数

document.body.addEventListener("mousemove", function() { var second = document.getElementById("second"); addMessage(second, "Event: mousemove"); }); var values = [0, 3, 2, 5, 7, 4, 8, 1]; values.sort(function(value1, value2){ return value1 - value2; });

当对一个数组中乱序数字排序时,sort无疑是最简便的方法,sort接受一个回调函数,并根据回调的数字进行排序,如果是正数就倒序反之正序

二、函数存储

In certain cases (for example, when we need to manage collections of callbacks that should be invoked when a certain event occurs), we want to store collections of unique functions. When adding functions to such a collection, a challenge we can face is determining which functions are new to the collection and should be added, and which are already resident and shouldn’t be added. In general, when managing callback collections, we don’t want any duplicates, because a single event would result in multiple calls to the same callback.

在某些情况下,比如我们需要去管理只有当被调用时触发的回调函数时,并且去存储一些具有独特功能的函数。 我们会面临以下的选择,那些函数是已经添加过的,避免重复添加,那些函数是没有添加过的应该新建。通常来说,当个回调会被多次调用,所以应该避免出现重复的事件。

var store = { nextId: 1, cache: {}, add: function(fn) { if (!fn.id) { fn.id = this.nextId++; this.cache[fn.id] = fn; //存储函数 return true; } } }; function ninja(){} console.assert(store.add(ninja), "Function was safely added."); console.assert(!store.add(ninja), "But it was only added once.");

上面的函数通过fn.id控制add只能被执行一次。当add被invoked时会在传入函数中写入值,再次调用发现值则避免调用。 我们来实现一个带有记忆功能的函数吧:

function isPrime(value){ if (!isPrime.answers){ isPrime.answers = {}; } // 如果不存在答案就创建一个属性存储答案,当然这个属性只会在第一次调用时创建 if (isPrime.answers[value] !== undefined) { return isPrime.answers[value];//如果发现包含了答案就返回 } var prime = value !== 1; // 1 is not a prime for (var i = 2; i < value; i++) { if (value % i === 0) { prime = false; break; } } return isPrime.answers[value] = prime; } console.assert(isPrime(5), "5 is prime!" ); console.assert(isPrime.answers[5], "The answer was cached!" );

上述函数实现了一个判断输入的数字是否时素数的功能。当第一次输入5时断言函数会返回false,并打印了语句"5 is prime!"

最新回复(0)