CNode

这样是不是就实现了单例模式?

问答
Ggwyy发布于9 年前最后回复9 年前4 回复4022 浏览0 收藏

class test {

constructor() {
    this.gwyy = "default";
}

setGwyy(gwyy) {
    this.gwyy = gwyy;
}

getGwyy() {
    return this.gwyy;
}

}

module.exports = new test();

外部输出直接是一个new的对象 这样别人require的话 应该都是这一份对象吧

查看回复

回复 (4)

B
burning0xb#2·9 年前

你可以看一下java的单例,饱汉模式和饿汉模式,这样的写法不是很正确。

D
dislido#3·9 年前

这种写法还是有办法搞出多个对象的,删掉test模块的缓存,重新require就是一个新对象了 test.js

class test {
	constructor() {
		this.gwyy = "default";
	}

	setGwyy(gwyy) {
		this.gwyy = gwyy;
	}

	getGwyy() {
		return this.gwyy;
	}
}
module.exports = new test();

解法

const obj1 = require('./test');
delete require.cache[Object.keys(require.cache).find(e => e.endsWith('test.js'))];
const obj2 = require('./test');
console.log(obj1 === obj2); // false
J
jiangzhuo#4·9 年前

symbol

参与回复
登录后即可参与回复。登录