使用模块中的defineProperty
假设在我的模块中我有这样的内容:
Object.defineProperty(Array.prototype,
'sayHello', {get: function(){ return "hello I'm an array" });
现在我想让导入该模块的任何脚本都可以看到此更改。这可能吗?
我尝试相应地修改 EXPORTED_SYMBOLS 但到目前为止我没有得到任何结果。
还有另一种方法可以实现同样的目的吗? (即加载向选定对象添加不可枚举属性的模块 - 如上面示例中的数组)
编辑:
遵循 Alnitak 下面关于 value:
和 get:
的评论..我
现在可以定义和使用这样的属性:
Object.defineProperty(Array.prototype, 'firstId' , {value: function(){return this[0].id}});
var a = [{id:'x'},{id:'y'}]
a.firstId()
它按预期返回
x
现在:是否可以将 DefineProperty 调用放入模块中,从脚本加载模块并期望该脚本的数组将充当上面那个?
EDIT2:
我正在使用 xulrunner 编写一个应用程序,并且使用 Components.utils.import() 来加载模块 - 我认为(可能是错误的)这个问题可以更普遍地提出......
Let's say in my module I have something like this :
Object.defineProperty(Array.prototype,
'sayHello', {get: function(){ return "hello I'm an array" });
Now I would like to make this change visible to any scripts that import the module. Is this possible ?
I tried to modify the EXPORTED_SYMBOLS accordingly but I got no results so far.
Is there another way to achieve the same thing ? (i.e. load modules that add not enumerable properties to selected objects - like Array in the example above)
EDIT:
Following the comment below by Alnitak about value:
and get:
...
I'm able now to define and use a property like this:
Object.defineProperty(Array.prototype, 'firstId' , {value: function(){return this[0].id}});
var a = [{id:'x'},{id:'y'}]
a.firstId()
that returns as expected
x
Now: is it possible to put the defineProperty invocation in a module, load a module from a script and expects that the Arrays of this script will act as the one above ?
EDIT2 :
I'm writing an application with xulrunner and I'm using Components.utils.import() to laod the module - I thought (probably wrongly) that the question could be put more generally ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
属性描述符中的
get:
类型可用于提供在运行时计算的只读值:如果属性只是只读常量,请使用
value:
value:这两个的用法就是:
您还应该使用
value:
类型添加一个函数作为原型的不可枚举属性,例如:usage :
同样地,
The
get:
type within a property descriptor can be used to supply a read-only value that's calculated at runtime:Use
value:
if the property is just a read-only constant value:The usage of both of those is just:
You should also use the
value:
type to add a function as a non-enumerable property of a prototype, e.g.:usage:
Likewise,