假设在我的模块中有这样的东西:
Object.defineProperty(Array.prototype,
'sayHello', {get: function(){ return "hello I'm an array" });现在,我想让这个更改对任何导入模块的脚本都可见。这是可能的吗?
我尝试相应地修改EXPORTED_SYMBOLS,但到目前为止还没有得到任何结果。
有没有其他方法可以达到同样的效果?(例如,加载模块将不可枚举的属性添加到所选对象-如上面示例中的Array )
编辑:
下面是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()来laod模块-我认为(可能是错误的)这个问题可以放在更一般的地方……
发布于 2011-09-26 22:12:08
属性描述符中的get:类型可用于提供在运行时计算的只读值:
Object.defineProperty(Array.prototype, 'sayHello', {
get: function() {
return "hello I'm an array";
}
});如果属性只是一个只读常量值,请使用value::
Object.defineProperty(Array.prototype, 'sayHello', {
value: "hello I'm an array"
});这两者的用法都是:
var hello = myArray.sayHello;您还应该使用value:类型将函数添加为原型的不可枚举属性,例如:
Object.defineProperty(Array.prototype, 'sayHello', {
value: function(o) {
return "hello I'm an array";
}
});用法:
var hello = myArray.sayHello();同样的,
https://stackoverflow.com/questions/7554509
复制相似问题