沧浪手机网站建设方案,淘宝运营公司,百度竞价账户,vs2017 做网站说明
今天阅读koa源码时,遇到Object.create,感觉对这个概念有点生疏,于是打开了MDN进行重新梳理传送门
Object.create()
直接套用官网的栗子
const person {isHuman: false,printIntroduction: function () {console.log(My name is ${this.name}. Am I human? ${this.i…说明
今天阅读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件事:
创建一个新对象.把原对象的属性和方法放在新对象的__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);将他们打印出来,查看继承到底做了些什么事情 可以看到:
Rectangle调用了Shape的constructor函数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__)逐级寻找.