yuanyuanbyte / Blog

圆圆的博客,预计写七个系列:JavaScript深入系列、JavaScript专题系列、网络系列、Webpack系列、Vue系列、JavaScript基础系列、HTML&CSS应知应会系列。
306 stars 125 forks source link

JavaScript 深入系列之 Object.create 的模拟实现 #114

Open yuanyuanbyte opened 2 years ago

yuanyuanbyte commented 2 years ago

本系列的主题是 JavaScript 深入系列,每期讲解一个技术要点。如果你还不了解各系列内容,文末点击查看全部文章,点我跳转到文末

如果觉得本系列不错,欢迎 Star,你的支持是我创作分享的最大动力。

Object.create 的模拟实现

Object.create()  方法用于创建一个新对象,使用现有的对象来作为新创建对象的原型(prototype)。

const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew'; // “name”是设置在“me”上的属性,而不是“person”上
me.isHuman = true; // 可以覆盖继承的属性

me.printIntroduction();
// "My name is Matthew. Am I human? true"

用法

Object.create(proto)

返回一个新对象,带着指定的原型对象及其属性。

该方法还可以传入第二个参数 propertiesObject 可选,如果该参数被指定且不为 undefined,则该传入对象的自有可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)将为新创建的对象添加指定的属性值和对应的属性描述符。这些属性对应于 Object.defineProperties() 的第二个参数。

用 Object.create() 实现类式继承

下面的例子演示了如何使用 Object.create() 来实现类式继承。这是一个所有版本 JavaScript 都支持的单继承。

// Shape - 父类
function Shape() {
  this.x = 0;
  this.y = 0;
}

// 父类方法
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - 子类
function Rectangle() {
  Shape.call(this); // call 父类构造函数.
}

// 子类继承父类
Rectangle.prototype = Object.create(Shape.prototype);

// 修改子类原型的构造函数
// 如果不把 Rectangle.prototype.constructor 指向 Rectangle,
// 它将采用 Shape (父级)的原型构造函数。
// 为了避免这种情况,我们将 Rectangle 的 prototype.constructor 设置为 Rectangle(子)。
Rectangle.prototype.constructor = Rectangle;

const rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?', rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

实现

思路:创建一个空的构造函数,将传入的对象作为这个构造函数的原型(prototype),最后返回构造函数的实例对象。

function create(obj) {
  function F() {}
  F.prototype = obj
  return new F()
}

参考这篇 https://www.cnblogs.com/ranyonsue/p/11201730.html 博客,里面一种 JS 实现继承的方式用到的就是上面的实现方式,其实就是手写了一个 Object.create 方法,来实现了继承。

在这里插入图片描述

查看全部文章

博文系列目录

交流

各系列文章汇总:https://github.com/yuanyuanbyte/Blog

我是圆圆,一名深耕于前端开发的攻城狮。

weixin