0%

javascript-interview-questions-08

JavaScript中new操作符做了哪些操作?

在JavaScript中,new 操作符用于创建一个对象。当你使用 new 操作符时,它执行以下步骤:

  1. 创建空对象
  2. 将新对象的 __prototype__属性链接到构造函数的 prototype 属性
  3. 执行构造函数中的代码,并将新对象绑定到 this 上。
  4. 返回新对象

下面是一个简单的例子:

1
2
3
4
5
6
7
function Person(name, age) {
this.name = name;
this.age = age;
}

const p = new Person('zdd', 40);
console.log(p);

面试官可能接着问,如何写一个函数,模拟new操作符的行为?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function NewPerson(fn, ...args) {
// Create an empty object
const obj = {};

// Set the prototype of the object to the prototype of the function
obj.__proto__ = fn.prototype;

// Call the function with the object as the context
const result = fn.apply(obj, args);

// Return the object
return result instanceof Object ? result : obj;
}

const p1 = NewPerson(Person, 'zdd', 40);
console.log(p1);

其实上面的代码可以简化一下,比如前两行代码其实可以用下面的一行代码代替。

1
const obj = Object.create(fn.prototype);

如何实现instanceof操作符?

instanceof操作符用于检查一个对象是否是一个类的实例。下面是一个简单的实现:

1
2
3
4
5
6
7
8
9
10
11
12
function myInstanceof(obj, constructor) {
let proto = obj.__proto__;
while (proto) {
if (proto === constructor.prototype) {
return true;
}
proto = proto.__proto__;
}
return false;
}

myInstanceof([1, 2, 3], Array); // true

__proto__属于非标准属性,所以不推荐使用。可以使用Object.getPrototypeOf来获取对象的原型。

1
2
3
4
5
6
7
8
9
10
function myInstanceof(obj, constructor) {
let proto = Object.getPrototypeOf(obj);
while (proto) {
if (proto === constructor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}