# new 实现原理

#### 原理

1. 创建一个空对象，构造函数中的 `this` 指向这个空对象
2. 这个新对象被执行 `[[原型]]` 连接
3. 执行构造函数方法，属性和方法被添加到 `this` 引用的对象中
4. 如果构造函数中没有返回其它对象，那么返回 `this`，即创建的这个的新对象，否则，返回构造函数中返回的对象

```javascript
function _new(fn, ...arg) {
    let obj = Object.create(fn.prototype);
    let ret = fn.apply(obj, arg);
    return ret instanceof Object ? ret : obj;
}
```

`Object.create()` 方法创建一个新对象，使用现有的对象来提供新创建的对象的 `__proto__`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bvct1742.gitbook.io/one-book/knowledge/js/new-shi-xian-yuan-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
