js bifrost令人难以置信的javascript功能

Welcome to The JS Bifrost, your pathway to a rock-solid foundation for God-level JavaScript. This is the next article in the series, which highlights certain JavaScript features and tricks to write efficient code.

欢迎来到JS Bifrost,这是通往神级JavaScript坚实基础的途径。 这是该系列的下一篇文章,重点介绍了某些JavaScript功能和编写高效代码的技巧。

Javascript is a weird and funny language, yet so beautiful and powerful. Javascript developers are always striving to learn something new and even if we have used it for years, we keep discovering new features & tricks every other time. This article is an attempt to unfold and revisit such features and tricks that are sparingly used but are really handy and useful.Let’s dive in.

Javascript是一种怪异而有趣的语言,却是如此美丽而强大。 Javascript开发人员一直在努力学习新的东西,即使我们已经使用了多年,但我们每隔一段时间就会不断发现新的功能和窍门。 本文旨在揭示并重新审视很少使用但非常方便实用的功能和技巧。

1.获取器和设置器 (1. Getters and Setters)

Getters and Setters allow us to have more control over object properties by controlling how to set & access them. Sometimes, we may want to perform an operation before/after the value has been updated or accessed. Getters and Setters provide a perfect way to do this. A Setter is automatically invoked on assignment and Getter is invoked when a property is accessed. get and set are the keywords for defining getters and setters respectively. Let’s see how they work:

GetterSetters通过控制设置和访问对象的属性,使我们可以更好地控制对象属性。 有时,我们可能想在更新或访问该值之前/之后执行操作。 GetterSetter提供了一种完美的方法。 在分配属性时,将自动调用Setter并在访问属性时调用Gettergetset是分别用于定义getter和setter的关键字。 让我们看看它们如何工作:

const user = {
_age: 20,
set age(value) {
// Adding checks before assigning the value
if (typeof value !== 'number' || value <= 0 || value > 100) {
console.log('Invalid Age');
return;
}
this._age = value;
}, get age() {
// We can do some processing & return modified value as we want
return `${this._age} years`;
}
}user.age = '26'; // Invalid age -> Setter is invokeduser.age = 26; // Setter is invoked & value gets assigned as it is validconsole.log(user.age); // "26 years" -> Getter is invoked

What’s going on here?We defined getters and setters for a property age in user object. As you can see, the property age does not directly exist in the object, rather we use another property _age to store & retrieve the actual value. Thus, age becomes a pseudo-property. Now, when we assign a value to user.age, the setter function is automatically invoked. It checks the conditions and assigns the value to _age property. Whenever we try to access user.age, the getter function invokes and returns a processed value using _age.

我们在用户对象的属性年龄中定义了吸气剂和吸气剂。 如您所见,属性age并不直接存在于对象中,而是使用另一个属性_age来存储和检索实际值。 因此, 年龄成为伪财产。 现在,当我们为user.age分配一个值时,setter函数将被自动调用。 它检查条件,并将值分配给_age属性。 每当我们尝试访问user.age ,getter函数都会使用_age调用并返回处理后的值。

Okay, but how to define getters and setters on an already defined object?With Object.defineProperty. Let’s see how that works:

好的,但是如何在已经定义的对象上定义getter和setter方法呢?使用Object.defineProperty 。 让我们看看它是如何工作的:

const user = {
_age: 20
};Object.defineProperty(user, 'age', {
set: function(value) {
if (typeof value !== 'number' || value <= 0 || value > 100) {
console.log('Invalid Age');
return;
}
this._age = value;
},
get: function() {
return `${this._age} years`;
}
});user.age = '123'; // "Invalid Age"
user.age = 12;
console.log(user.age); // "12 years"

We can define Getters and Setters in classes as well, in the same way as defined above.

我们也可以在类中定义GetterSetter 与上述定义相同。

2.一元+&-运算符 (2. Unary + & - Operators)

A unary operation is an operation with only one operand. Unary + & - operators attempt to convert the operand to number type, the only difference being the unary - makes the number negative.Many a times, we encounter a scenario where we need to convert a string to a number. These operators come to the rescue by just prefixing them to the given string. Let’s see how they work:

一元运算是只有一个操作数的运算。 一元+-运算符尝试将操作数转换为数字类型,唯一的区别是一元-使数字负数。很多次,我们遇到了需要将字符串转换为数字的情况。 这些运算符通过在给定字符串的前缀之前进行救援。 让我们看看它们如何工作:

+'78' // 78
+'text' // NaN
+'-7' // -7
+true // 1
+false // 0
+null // 0
+{} // NaN
+new Date(); // 1599153225988 -> Current Timestamp// Similarly,-'78' // -78
-'text' // NaN
-true // -1
-false // -0
-null // -0
-{} // NaN

3.求幂(**)运算符 (3. Exponentiation ( ** ) Operator)

This operator is useful to quickly find the power of a number raised to a certain number. If you want to find x to the power y, simply use x ** y.

此运算符对于快速找到加到特定数字的数字的幂很有用。 如果要找到x的幂y,只需使用x ** y

console.log(2 ** 3); // 8console.log(2 ** 3 ** 2); // 512console.log((2 ** 3) ** 2); // 64

As an added advantage, it also accepts BigInts as operands.

另外一个优点是,它也接受BigInts作为操作数。

4.在运算符中 (4. in Operator)

in operator can be used to quickly check if a specified property is present in an object.Syntax: prop in object

in运算符可用于快速检查对象中是否存在指定属性。语法: prop in object

const user = {
age: 23,
fullName: 'Test'
};console.log('age' in user); // truelet colours = ['red', 'green', 'blue'];console.log(2 in colours); // true
// As index 2 is present in arrayconsole.log('green' in colours); // false
// You must specify the index number, not the value at that indexconsole.log('length' in colours); // true
// As length is an Array property

Keep in mind that the in operator returns true even if the property is present in the prototype chain.

请记住,即使原型链中存在该属性, in运算符也将返回true。

console.log('toString' in {}); // true

5. new.target属性 (5. new.target property)

This property is useful to detect whether a function or constructor was called using the new operator. It gives us a reference to that class or constructor function. The new.target pseudo-property is available in all the functions. However, in normal function calls, new.target is undefined.

此属性对于检测是否使用new运算符调用了函数或构造函数很有用。 它为我们提供了对该类或构造函数的引用。 new.target伪属性在所有函数中均可用。 但是,在正常的函数调用中, new.target是未定义的。

function User() {
if (!new.target) {
console.log('Normal function call');
} else {
console.log('Instance created using new operator');
}
console.log(new.target);
}const testUser = new User();
// Instance created using new operator
// Logs the reference to function UserUser();
// Normal function call
// undefined -> No reference

You may think, why do we need to check if an instance was created with new operator? Consider the following example:

您可能会想,为什么我们需要检查实例是否使用new运算符创建? 考虑以下示例:

let colour = 'red';// Constructor function
const Car = function(colour) {
this.colour = colour;
};const myCar = new Car('blue');
console.log(myCar.colour); // "blue"
console.log(window.colour); // "red"const hisCar = Car('blue'); // Direct function call
console.log(hisCar.colour); // Error
console.log(window.colour); // "blue"
// overwritten the global variable: colour

As we saw above, the global variable colour got updated unknowingly as ‘this’ is pointing to a window inside the function, which is called directly. To avoid such mishaps, we can rely on new.target property.

正如我们在上面看到的那样,全局变量colour在不知不觉中得到了更新,因为“ this”指向函数内部的一个窗口,该窗口被直接调用。 为了避免这种不幸,我们可以依靠new.target属性。

6.字符串替换可以接受回调函数 (6. String Replace can accept a callback function)

Many a times, we use the replace method on strings with regex/string as the first parameter and string to be replaced as the second.

很多时候,我们对正则表达式/字符串作为第一个参数,对字符串进行替换作为第二个参数,对字符串使用replace方法。

const newStr = str.replace(regexp|substr, replacement);

const newStr = str .replace( regexp | substr , replacement );

It replaces all the matches with the provided replacement string. However, we can have more control over the replacement by providing a callback function as a second parameter. Consider an example:

它将所有匹配项替换为提供的替换字符串。 但是,通过提供回调函数作为第二个参数,我们可以更好地控制替换。 考虑一个例子:

const output = '4 12 27 32 15'.replace(/\d+/g, '#');
console.log(output); // # # # # #

This is a simple replacement, where we are replacing each number with ‘ # ’. What if we wanted to replace only the numbers > 20? We cannot simply do that with regex alone, right? We can achieve that with a callback function.

这是一个简单的替换,我们将每个数字替换为“#”。 如果我们只想替换数字> 20,该怎么办? 我们不能仅仅使用正则表达式来做到这一点,对吗? 我们可以使用回调函数来实现。

const output = '4 12 27 32 15'.replace(/\d+/g, function(match) {
return +match > 20 ? '#' : match;
});console.log(output); // 4 12 # # 15

Notice how we used the unary + operator to convert a string to a number 🙂.

注意我们如何使用一元+运算符将字符串转换为数字🙂。

7.格式化JSON (7. Formatting JSON)

While dealing with APIs, we need to stringify objects - a very common scenario for a web developer. We simply use JSON.stringify() to achieve that. You know how ugly it is to visualize such JSON strings 😅. Look at the one below:

在处理API时,我们需要对对象进行字符串化-这是Web开发人员非常普遍的情况。 我们只需使用JSON.stringify()即可实现。 您知道可视化此类JSON字符串是多么丑陋。 看下面的一个:

{"name":{"firstName":"John","lastName":"Doe"},"age":26,"experience":6,"category":{"user":{"permission":"all"}}}

And it keeps getting uglier when we have larger & deeply nested objects. However, JSON.stringify() method also allows us to indent such strings, for better readability.It accepts two optional parameters.

当我们有更大且深度嵌套的对象时,它会变得越来越难看。 但是, JSON.stringify()方法还允许我们缩进此类字符串,以提高可读性,它接受两个可选参数。

  • Replacer function - Allows us to filter the properties of an object to be stringified.

    替换函数-允许我们过滤要被字符串化的对象的属性。
  • Space - A number or a string used to insert white space into the output JSON string. With a number, you can specify the number of spaces you want and with string, space characters like ‘\t’ (tab).

    空格-用于在输出JSON字符串中插入空格的数字或字符串。 使用数字,您可以指定所需的空格数,并使用字符串,'\ t'(制表符)之类的空格字符来指定。
const output = JSON.stringify({
name: {
firstName: 'John',
lastName: 'Doe',
},
age: 26,
experience: 6,
category: {
user: {
permission: 'all'
}
}
}, null, '\t');console.log(output);// Shows following formatted output:
{
"name": {
"firstName": "John",
"lastName": "Doe"
},
"age": 26,
"experience": 6,
"category": {
"user": {
"permission": "all"
}
}
}

结论 (Conclusion)

I know there are many other features and tricks apart from these, which we might not be aware of. If you know any such interesting use cases, please share those in the comments section.

我知道除了这些以外,还有许多其他功能和窍门,我们可能不会意识到。 如果您知道任何此类有趣的用例,请在评论部分中共享这些用例。

Image for post

If you enjoyed reading this article, please share :) Thank you!

如果您喜欢阅读本文,请分享:)谢谢!

Keep Coding JavaScript ❤️

继续编码JavaScript❤️

Watch out our ‘The JS Bifrost’ series for more such amazing articles.

请关注我们的“ JS Bifrost ”系列,以获取更多此类惊人的文章。

翻译自: https://medium.com/globant/the-js-bifrost-incredible-javascript-features-587b78865e67

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值