Home>Article>Web Front-end> Share some little-known hidden syntax or techniques in JavaScript

Share some little-known hidden syntax or techniques in JavaScript

青灯夜游
青灯夜游 forward
2020-11-04 17:53:48 1760browse

Share some little-known hidden syntax or techniques in JavaScript

javaScript is often considered the easiest language to get started with and the hardest to master, and I couldn’t agree more. This is because JavaScript is a very old and very flexible language with arcane syntax and outdated features.

I've been using JavaScript for many years, and until now, I occasionally discover some hidden syntax or trick that I didn't know about before. While these properties may be less well known, they are still well known.

Note: Variable promotion, closures, proxies, prototypal inheritance, asynchronous waiting, generators, etc. are not included here.

void operator

JavaScript has a unary void operator. You may have seen it used as void(0) or void 0. The function of void is to return undefined. The operand on the right side of it will be calculated normally, but no matter what the result is, void will return undefined. Using "0" is just a convention. It is not necessary to use '0', it can be any valid expression, like void , it will still return undefined.

Share some little-known hidden syntax or techniques in JavaScript

// void operator void 0 // returns undefined void (0) // returns undefined void 'abc' // returns undefined void {} // returns undefined void (1 === 1) // returns undefined void (1 !== 1) // returns undefined void anyfunction() // returns undefined

Why create a special keyword to return undefined instead of just returning undefined? Sounds a bit redundant, doesn’t it?

Fun Facts

Actually, prior to ES5, in most browsers, the original undefined = "abc" could be assigned a new value. So, in those days, using void was a way to ensure that the original value of undefined was always returned.

Constructor brackets are optional

Yes, the brackets we add after the class name when calling the constructor - completely optional! (provided that there is no need to Any parameters passed to the constructor)

The following two code styles are considered valid JS syntax and the results are the same!

Share some little-known hidden syntax or techniques in JavaScript

// Constructor with brackets const date = new Date() const month = new Date().getMonth() const myInstance = new MyClass() // Constructor without brackets const date = new Date const month = (new Date).getMonth() const myInstance = new MyClass

Yes Omitting parentheses for IIFE (immediately executed function)

The syntax of IIFE (immediately invoked function expression) has always been a bit strange to me, why are there so many parentheses?

Actually, these extra brackets are just to tell the JavaScript parser that the code to be parsed is a function expression, not a function. Knowing this, you can imagine that there are many ways to omit those extra parentheses and still work efficiently with IIFE.

Share some little-known hidden syntax or techniques in JavaScript

// IIFE (function () { console.log('正常形式的 IIFE 调用') })() // 清爽的 IIEF void function() { console.log('酷酷的 IIFE 调用') }()

voidThe operator tells the parser that the code is a function expression. Therefore, we can skip the parentheses around the function definition. Guess what? We can use any unary operator (void, , !, -, etc) and it will still work!

Isn’t this simpler than the original way of writing and has more B cells? What's up?

But, if you are a keen observer, you may be thinking, don't unary operators affect the result returned by IIFE?

It will affect the results. But the good news is that if you just return the result and store it in some variable, then you don't need the extra parentheses.

Share some little-known hidden syntax or techniques in JavaScript

#with declaration

JavaScript has a with statement block, and with is actually a keyword in JS. The syntax of the with block is as follows:

Share some little-known hidden syntax or techniques in JavaScript

#The with statement can be conveniently used to reference properties that already exist in a specific object, but it cannot be used to add properties to the object. To create new properties on an object, you must explicitly reference the object.

Share some little-known hidden syntax or techniques in JavaScript

Fun Fact

with blocks looks cool, right? It's even better than object destruction. Well, not really.

Using the with statement is generally discouraged as it is deprecated and completely prohibited in strict mode. It turns out that using with blocks increases some performance and security issues in the language.

Function constructor

Function statements are not the only way to define new functions. Functions can be dynamically defined using the function() constructor and the new operator.

Share some little-known hidden syntax or techniques in JavaScript

Interesting Facts

Function constructor is the mother of all constructors in JavaScript. Even the constructor of Object is a Function constructor. And Function's own constructor is also Function itself.

Thus, calling object.constructor.constructor...enough times will eventually return the Function constructor on any object in JavaScript.

函数属性

我们都知道函数是JavaScript中的第一类对象。因此,没有人阻止我们向函数添加自定义属性。在 JS 中这样做是有效的,然而,它很少被使用。

那么我们什么时候要这样做?

这里有一些很好的用例。例如,

可配置函数

假设我们有一个函数叫做 greet。我们希望函数根据不同的地区打印不同的问候消息,这个区域设置也应该是可配置的。我们可以在某个地方维护全局 locale 变量,也可以使用如下所示的函数属性实现该函数

Share some little-known hidden syntax or techniques in JavaScript

function greet () { if (greet.locale === 'ch') { console.log('中国,你好') } else if (greet.locale === 'jp') { console.log('扣你机哇!') } else { console.log('Hello World') } } greet() // Hello World greet.locale = 'ch'; greet() // 中国,你好

具有静态变量的函数

另一个类似的例子。比方说,希望实现一个生成有序数字序列的数字生成器。通常您将使用带有静态计数器变量的 Class 或 IIFE 来跟踪最后一个值。这样我们就限制了对计数器的访问,同时也避免了使用额外的变量污染全局空间。

但是,如果我们希望能够灵活地读取甚至修改计数器,而又不污染全局空间,该怎么办呢?

我们仍然可以创建一个类,有一个计数器变量和一些额外的方法来读取它;或者我们可以偷懒,使用函数自定义的属性。

Share some little-known hidden syntax or techniques in JavaScript

Arguments 的属性

我相信你们大多数人都知道函数中的arguments对象。它是一个类似数组的对象,可以在所有函数中使用。它具有在调用函数时传递给函数的参数列表。但它也有一些其他有趣的性质:

  • arguments.callee: 当前调用的函数

  • arguments.callee.caller:调用当前函数的函数

Share some little-known hidden syntax or techniques in JavaScript

注意:虽然ES5禁止在严格模式下使用callee & caller,但在许多编译后的库中仍然很常见。所以,学习它们是值得的。

标记模板字符串

模板字符串文字是ES6中许多很酷的附加内容之一,但是,知道标记模板字符串是比较少的?

1Share some little-known hidden syntax or techniques in JavaScript

标记模板字符串允许你通过向模板字符串添加自定义标记来更好地将模板文字解析为字符串。Tag只是一个解析器函数,它获取字符串模板解释的所有字符串和值的数组,标记函数应返回最终字符串。

在下面的例子中,我们的自定义标记 —— 高亮显示,解释模板文本的值,并将解释后的值包装在结果字符串中,使用元素进行高亮显示。

1Share some little-known hidden syntax or techniques in JavaScript

Getters & Setters

在大多数情况下,JavaScript对象是简单的。假设我们有一个 user 对象,我们试图使用user访问它的age属性。使用 user.age 得到年龄属性的值,如果没有定义,我们得到未定义的值。

但是,并不一定要这么简单。JavaScript 对象具有 getter 和 setter 的概念。我们可以编写自定义Getter函数来返回我们想要的任何东西,而不是直接返回对象上的值,设置一个值也是一样。

这使我们可以在获取或设置字段时拥有强大的能力,如virtual fieldsfield validationsside-effects

1Share some little-known hidden syntax or techniques in JavaScript

逗号操作符

JavaScript有一个逗号操作符。它允许我们在一行中用逗号分隔多个表达式,并返回上一个表达式的结果。

1Share some little-known hidden syntax or techniques in JavaScript

在这里,所有表达式都将被求值,结果变量将被赋值给expressionN返回的值。

我们经常在for循环中使用了逗号操作符

for (var a = 0, b = 10; a <= 10; a++, b--)

有时在一行中编写多个语句

function getNextValue() { return counter++, console.log(counter), counter }

或者

const getSquare = x => (console.log (x), x * x)

+ 加号操作符号

想要快速地将字符串转换为数字吗?

只需在字符串前面加上+运算符。加号运算符也适用于负数、八进制、十六进制、指数值。更重要的是,它甚至可以转换 Date 或者 Moment.js对象的时间戳!

1Share some little-known hidden syntax or techniques in JavaScript

!! Operator

Technically speaking, it is not a separate JavaScript operator. It's just the JavaScript inverse operator used twice.

If the expression is a true value, return true; otherwise, return false.

1Share some little-known hidden syntax or techniques in JavaScript

~ Non-Operators

Let's face it - no one cares about bitwise operators. When can we use it!

Here is an everyday use case regarding the tilde or bitwise NOT operator.

It turns out that the NOT operator is valid when used with numbers ~N => -(N 1) This expression only evaluates to "0" when N is -1.

We can take advantage of this by putting ~ in front of the indexOf(...) function, which performs a boolean check if the item exists in the string or array.

1Share some little-known hidden syntax or techniques in JavaScript

Note: ES6 and ES7 added a new .include() method for strings and arrays respectively. Of course, this is a cleaner way to check if an item exists in an array or string than the tilde operator.

Use of tags

The break and continue statements can be used in conjunction with the lebel statement to return to a specific location in the code. Used for nested loops to reduce the number of loops.

1Share some little-known hidden syntax or techniques in JavaScript

Recommended tutorial: "JavaScript Video Tutorial"

The above is the detailed content of Share some little-known hidden syntax or techniques in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete