gpt4 book ai didi

javascript - node.js 需要 Object.prototype 吗?

转载 作者:行者123 更新时间:2023-11-29 22:05:11 24 4
gpt4 key购买 nike

我对 node.js require 系统有点困惑。

我知道如何exportmodule.export 函数的required 组件,但不确定如何使用原型(prototype)增强js 对象.

例如,我有一段代码可以使用 prototype.watch 方法增强 js 对象。

我会将这段代码放在我自己的 npm 包中,并使用 Node require 导入。

执行此操作的最佳方式是什么?我是否需要将此代码重构为导出函数并需要在 require 之后执行?谢谢。

if (!Object.prototype.watch)
{
Object.defineProperty(Object.prototype, "watch",
{
enumerable: false,
configurable: true,
writable: false,
value: function(prop, handler)
{
var
oldval = this[prop],
newval = oldval,
getter = function()
{
return newval;
},
setter = function(val)
{
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
};

if (delete this[prop])
{ // can't watch constants
Object.defineProperty(this, prop,
{
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
});
}

// object.unwatch
if (!Object.prototype.unwatch)
{
Object.defineProperty(Object.prototype, "unwatch",
{
enumerable: false,
configurable: true,
writable: false,
value: function(prop)
{
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
}

最佳答案

node.js 中的所有模块共享相同的全局范围。

只需 require() 它,您对全局对象所做的任何更改都会传播。

关于javascript - node.js 需要 Object.prototype 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355948/

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