gpt4 book ai didi

javascript - 如何使用 `requires` 重置类原型(prototype)

转载 作者:行者123 更新时间:2023-11-29 21:32:55 25 4
gpt4 key购买 nike

为了举例,这里有一些人为的东西:

var util = require('util');
var Me = require('./me.js');

console.log(util.inspect(Me.prototype.something.toString())); // #1

Me.prototype.name = function() {
console.log('different');
};

console.log(util.inspect(Me.prototype.something.toString())); // #2

// re-init prototype
var Me = require('./me.js');
console.log(util.inspect(Me.prototype.something.toString())); // #3

输出:

'function () {\n    console.log(\'original\');\n}'
'function () {\n console.log(\'different\');\n}'
'function () {\n console.log(\'different\');\n}'

为什么 require 调用不重新初始化 Me 类原型(prototype)?

最佳答案

来自 Nodejs 文档,LINK

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

关于javascript - 如何使用 `requires` 重置类原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35667472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com