JavaScript教程 / 全部 / 前端 / 技术 · 2022年5月6日 0

21 – JavaScript 中少有人知道的技巧

原文链接:https://dev.to/bhagatparwinder/lesser-known-javascript-tricks-kjj

构造函数的括号可选

const newDate = new Date(); // valid
const myClass = new MyClass(); // valid

const anotherDate = new Date; // Also valid
const myClass = new MyClass; // You bet this is valid

只有当构造函数需要参数时,括号才是必须的。

With 语句

with 语句是不推荐使用的,并且在 ES5 的严格模式下是禁用的。

with 扩展了语句的作用域,with 会把传入参数上的所有属性都附加到作用域链上。

const person = {
    name: "Parwinder",
    age: 33,
    work: "Software Architect"
}

with (person) {
    console.log(`Hi, I am ${name}, and I am ${ age } years old. I work as a ${work}.`);
    // Hi, I am Parwinder, and I am 33 years old. I work as a Software Architect.
}

Function 的参数

每个函数(除了箭头函数)有一个 arguments 类数组对象,包括所有传递给函数的参数。

function foo(a, b, c) {
  console.log(arguments[0]); // 1
  console.log(arguments[1]); // 2
  console.log(arguments[2]); // 3
}

foo(1, 2, 3);

arguments 有两个属性:

  1. arguments.callee: 被调用的函数;
  2. arguments.callee.caller: 调用函数的函数;
function foo(){
    console.log(arguments)
    console.log(arguments.callee)
    console.log(arguments.callee.caller)       
}

function fun(){
    foo()
}

fun() 

结果:

注意:就像上面的 with 语句,ES5 的严格模式下 callee 和 caller 是被禁止的。

纯对象

一个纯对象是在其 prototype 上没有方法的。

const x = {};

上面创建了一个对象,但其 prototype 上有 constructor 属性和 hasOwnProperty、isPrototypeOf 和 toString 这样的方法。

const x = Object.create(null);

create(null) 生成了一个没有 prototype 的对象!

移出数组中的重复项

const arr = [1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 6, 6, 6, 7, 8, 9];
const arrWithoutDuplicates = [...new Set(arr)];
console.log(arrWithoutDuplicates); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Set 中的值都是唯一的,当数组经过 Set 包装后,我们只需要通过 spread(…)操作符分解到一个空的数组就行了。

可选链

无论何时你需要获取嵌套对象上的属性且你不知道它是否存在,你需要向下面这样做:

const nestedObject = {
    name: "Parwinder",
    details: {
        age: 33,
        cars: {
            first: "jeep",
            second: "tesla",
            accessories: {
                x: 200,
                y: 300
            }
        }
    }
}

if (nestedObject &&
    nestedObject.details &&
    nestedObject.details.cars &&
    nestedObject.details.cars.accessories) {
    console.log(nestedObject.details.cars.accessories.x); // 200
}

可选链(Optional Chaining)就是来解决这个繁琐问题的,通过可选链( Options Chaining)你可以这样做:

const nestedObject = {
    name: "Parwinder",
    details: {
        age: 33,
        cars: {
            first: "jeep",
            second: "tesla",
            accessories: {
                x: 200,
                y: 300
            }
        }
    }
}

console.log(nestedObject?.details?.cars?.accessories?.x); // 200

注意:Optional Chaining 出现在 ES2020/ES11 规范里,来看看这里:https://tc39.es/ecma262/2020/。