Skip to content

Commit

Permalink
feat: 添加实现 new 笔记
Browse files Browse the repository at this point in the history
  • Loading branch information
yangjin committed Nov 24, 2019
1 parent 3e7c967 commit 50927ce
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
5 changes: 3 additions & 2 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,14 +222,15 @@ module.exports = {
'this',
'对象、原型和原型链',
'实现继承',
'实现new',
'实现call,apply和bind',
'实现instanceof',
'深拷贝和浅拷贝',
'节流函数和防抖函数',
'高阶函数',
'函数柯里化',
'EventEmitter',
'实现call,apply和bind',
'实现Promise',
'实现instanceof',
'实现异步打印',
'数组去重,扁平化和最值',
'数组乱序',
Expand Down
32 changes: 32 additions & 0 deletions docs/javaScript/实现new.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# 实现 new

我们知道使用 `new` 操作符,这种方式调用构造函数实际上会经历 4 个步骤:

1. 创建(或者说构造)一个全新的对象;
2. 这个新对象会被执行 `[[Prototype]]` 链接;
3. 这个新对象会被绑定到函数调用的 `this`
4. 如果函数没有返回其他新对象,那么 `new` 表达式中的函数调用会自动返回这个新对象。

```js
function Foo(name, age) {
this.name = name;
this.age = age;
}
var bar = new Foo('Vue', 20);
console.log(bar); // {name: "Vue", age: 20}
```

按照这个过程实现一个 `new` 操作符:

```js
function myNew() {
var obj = new Object(); // 创建一个新对象
var Ctor = [].shift.call(arguments);
obj.__proto__ = Ctor.prototype; // 执行 [[Prototype]] 链接
var result = Ctor.apply(obj, arguments); // 绑定到函数调用的 this
return result === 'object' ? result : obj; // 返回对象
}

var baz = myNew(Foo, 'Vue', 20);
console.log(baz); // {name: "Vue", age: 20}
```

0 comments on commit 50927ce

Please sign in to comment.