关于实例化koa-router
来源:2-5 Koa开发RESTful接口,GET&POST获取数据及数据格式化方法【进阶篇】
qq_那些荒废流年
2019-10-15 16:21:24
老师您好,我想问下在require koa-router后,不是要将Router new一下才能得到实例对象吗?这里为什么没有new,而是直接调用了require的koa-router?
1回答
Brian
2019-10-15
哈哈,同学,如果是这样写,就是偷懒了~~~
正确的做法,是需要写一个new的,参考资料
要解释你这个问题,需要解释下面两个问题:
new运算符在干嘛?
答:new运算符,是新建了一个实例,这个实例在内存中单独分配了一个区域给我们的函数fn,那么这个实例里面的任何操作,与函数的定义fn无关。
require方法在干嘛?
这里我们举一个例子:
// module.js
module.exports = function(){
return "Helo World";
}
我们去使用require去引用module.js的时候,其实就是在我们的当前文件中,引用了一个函数fn:
var f = require('./module');
console.log(f()); //hello world 这里其实就是一个内存中的实例,
那么这种玩法有什么弊端?
没有使用new运算符,则会共用一个内存区域,那么可能会导致变量或者对象被相互影响的情况。如:
// module.js
var HelloWorld = (function () { this.greeting = “Hello, World”; return this;})();
module.exports = HelloWorld;
// test.js
var helloWorldA = require(‘./module.’);
var helloWorldB = require(‘./module.’);
helloWorldA.greeting = "Hi";
console.log(helloWorldA.greeting); // 打印 Hi
console.log(helloWorldB.greeting); // 打印 Hi
// test1.js
var helloWorldA = new (require(‘./module.’));
var helloWorldB = new (require(‘./module.’));
helloWorldA.greeting = "Hi";
console.log(helloWorldA.greeting); // 打印 Hi
console.log(helloWorldB.greeting); // 打印 Hello, World
GET到没有?
相似问题