返回

一文搞懂JS五个常考手写函数:小白也能轻松理解

前端

前言

在 JavaScript 中,手写函数是一个常见的面试题,也是前端开发人员必备的技能之一。通过手写这些函数,可以帮助你深入理解 JavaScript 的底层原理和运行机制,从而写出更加高效、健壮的代码。

一、new

new 运算符是用于创建新对象的函数。它的语法如下:

new constructor([arguments])

其中,constructor 是要创建的对象的构造函数,arguments 是传递给构造函数的参数。

例如,创建一个 Person 对象:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person = new Person('John Doe', 30);

console.log(person.name); // 'John Doe'
console.log(person.age); // 30

二、call 和 apply

call 和 apply 都是用于调用函数的方法。它们的语法如下:

Function.prototype.call(context, [arguments])
Function.prototype.apply(context, [arguments])

其中,Function.prototype.call() 方法将函数的 this 设置为 context,并用参数 arguments 调用该函数。

Function.prototype.apply() 方法与 Function.prototype.call() 类似,但参数 arguments 是一个数组。

例如,调用一个函数并打印结果:

function greet() {
  console.log(this.name);
}

const person = {
  name: 'John Doe'
};

greet.call(person); // 'John Doe'
greet.apply(person); // 'John Doe'

三、bind

bind 方法是用于创建函数的一个新版本的方法。它的语法如下:

Function.prototype.bind(context, [arguments])

其中,Function.prototype.bind() 方法将函数的 this 关键字设置为 context,并返回一个新的函数,该函数的参数是 arguments。

例如,创建一个函数并返回一个新版本:

function greet() {
  console.log(this.name);
}

const person = {
  name: 'John Doe'
};

const greetPerson = greet.bind(person);

greetPerson(); // 'John Doe'

四、instanceof

instanceof 运算符是用于判断一个对象是否属于某个类的方法。它的语法如下:

object instanceof constructor

其中,object 是要判断的对象,constructor 是要判断的类。

例如,判断一个对象是否属于 Person 类:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person = new Person('John Doe', 30);

console.log(person instanceof Person); // true

总结

在本文中,我们详细解释了五个常见的手写函数:new、call、apply、bind 和 instanceof。这些函数对于理解和使用 JavaScript 语言是不可或缺的。通过手写这些函数,可以帮助你深入理解 JavaScript 的底层原理和运行机制,从而写出更加高效、健壮的代码。