koa2 app.context
当在使用koa2
框架时,好奇为什么通过 app.context.xxx
添加的属性可以通过ctx.xxx
调用,于是乎看了下相关源码
在application.js
文件中,看到了构造函数中初始化部分代码如下:
this.middleware = [];//用来存储中间件,也就是洋葱模型的核心
this.context = Object.create(context);//实例化this.context对象
this.request = Object.create(request);//实例化this.request对象
this.response = Object.create(response);//实例化this.response对象
this.context = Object.create(context);
通过Object.create
实例化一个对象this.context
,这个对象将会继承context
对象的所有属性和方法。通过Object.create
方法新创建的this.context
是一个空对象{}
;
createContext(req, res) {
const context = Object.create(this.context);
const request = context.request = Object.create(this.request);
const response = context.response = Object.create(this.response);
context.app = request.app = response.app = this;
context.req = request.req = response.req = req;
context.res = request.res = response.res = res;
request.ctx = response.ctx = context;
request.response = response;
response.request = request;
context.originalUrl = request.originalUrl = req.url;
context.state = {};
return context;
}
继续往下查看,可以看到一个 createContext
方法,该方法中第一条语句 const context = Object.create(this.context);
也就是说当我们通过app.context.xxx
添加某个属性时,由于通过Object.create(this.context)
继承了添加在app.context
对象上的属性,因此可以通过ctx.xxx
直接调用。
补充Object.create()
Object.create
和Object.setPrototypeOf()
都可以实现继承,但是由于Object.setPrototypeOf()
并不仅仅只是修改实例的[[Prototype]]
的指向,而是会影响所有访问过那些修改过[[Prototype]]
对象的代码,从而影响代码性能。
Object.create
该方法接收两个参数,一个作为新对象原型的对象,另一个是定义新对象额外的属性(第二个参数可选)。然后以这个对象为原型,返回一个新的实例对象。该实例完全继承原型对象的属性。
const obj1 = {obj1: 'test'};
const inherit = Object.create(obj1);
console.log(obj1);//{obj1: "test"}
console.log(inherit);//{}
console.log(inherit.obj1);//test
console.log(inherit.obj1 === obj1.obj1);//true
Object.getPrototypeOf(inherit) === obj1;//true
//补充
inherit.__proto__ === obj1;//true 不建议使用__proto__,性能原因
obj1.o = [1,2,3];
console.log(obj1);//{obj1: "test", o: [1, 2, 3]}
console.log(inherit.o);// [1, 2, 3]
补充:
console.log(inherit)
时,对象本身是没有属性的,其所继承的属性在__proto__
属性上