javascript --- > Object.create的阅读

说明

  • 今天阅读koa源码时,遇到Object.create,感觉对这个概念有点生疏,于是打开了MDN进行重新梳理
  • 传送门

Object.create()

  • 直接套用官网的栗子
const person  = {
	isHuman: false,
	printIntroduction: function () {
		console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
	}
}
const me = Object.create(person);
console.log(me);

在这里插入图片描述

  • 上面解释了创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
  • 即做了2件事:
  1. 创建一个新对象.
  2. 把原对象的属性和方法放在新对象的__proto__属性中

好处

  • 个人认为.解决了对象赋值的浅拷贝问题
  • 由于javascript的对象类型是引用类型(《JavaScript高级程序设计》(第三版)),如果使用正常的赋值法,如下:
const me = person;
me.isHuman = true;
console.log(person.isHuman);

在这里插入图片描述
可以看到,我们对me的操作,直接影响到person了.


使用Object.create来实现类式继承

  • 先找到javascript中,类的继承究竟做了哪些事情
  • 假设现在有类Shape如下:
class Shape {
	constructor(x, y) {
		this.x = 0;
		this.y = 0;
	}
	moved(x, y){
		this.x += x;
		this.y += y;
		console.log('Shape moved');
	}
}
  • 假设类Rectangle继承Shape
class Rectangle extends Shape{
	constructor(x, y){
		super();
	}
}
const rect = new Rectangle();
const shape = new Shape();
console.log('rect', rect);
console.log('shape', shape);
  • 将他们打印出来,查看继承到底做了些什么事情
    在这里插入图片描述
  • 可以看到:
  1. Rectangle调用了Shape的constructor函数
  2. Rectangle原型的原型继承了Shape的原型

  • 先实现Shape类
function Shape (x, y) {
	this.x = 0;
	this.y = 0;
}
Shape.prototype.moved = function (x, y){
	this.x += x;
	ths.y += y;
	console.log('Shape moved');
}
const shape = new Shape();
console.log('shape', shape);

在这里插入图片描述

  • 在Rectangle类中调用Shape并将作用域绑定到当前作用域,即可实现this.x =0; this.y = y
function Rectangle (x, y) {
	Shape.apply(this);
}
const rect = new Rectangle();
console.log('rect');

在这里插入图片描述
现在有2个点没有解决:
3. Rectangle沿着原型链的构造函数找不到Shape
4. moved方法没有继承

想到Object.create方法,是创建一个新对象,并把该对象的属性和方法都挂在__proto__属性上,有如下继承方案:

Rectangle.prototype = Object.create(Shape.prototype);
const rect = new Rectangle();
console.log('rect', rect);

在这里插入图片描述
可以看到,基本上继承成功了,只是Rectangle的构造函数(constructor)丢了.只需要重新带上即可

Rectangle.prototpe.constructor = Rectangle;

总结

  • 如果想要某个对象继承另外一个对象所有的属性和方法,且新对象的操作不会影响到原来的对象.可以使用Object.create方式赋值.
  • 当在某个对象上找不到方法是,会顺着原型链(prototype, 浏览器显示为 __proto__)逐级寻找.
发布了177 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/103498382