From 50927ce677428f022157d51b75064850f8a102a9 Mon Sep 17 00:00:00 2001 From: yangjin Date: Sun, 24 Nov 2019 12:11:13 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=AE=9E=E7=8E=B0=20?= =?UTF-8?q?new=20=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/.vuepress/config.js | 5 +-- .../\345\256\236\347\216\260new.md" | 32 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 "docs/javaScript/\345\256\236\347\216\260new.md" diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 3701f2af..bec22471 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -222,14 +222,15 @@ module.exports = { 'this', '对象、原型和原型链', '实现继承', + '实现new', + '实现call,apply和bind', + '实现instanceof', '深拷贝和浅拷贝', '节流函数和防抖函数', '高阶函数', '函数柯里化', 'EventEmitter', - '实现call,apply和bind', '实现Promise', - '实现instanceof', '实现异步打印', '数组去重,扁平化和最值', '数组乱序', diff --git "a/docs/javaScript/\345\256\236\347\216\260new.md" "b/docs/javaScript/\345\256\236\347\216\260new.md" new file mode 100644 index 00000000..5b6a887c --- /dev/null +++ "b/docs/javaScript/\345\256\236\347\216\260new.md" @@ -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} +``` \ No newline at end of file