开发者

use defineProperty from a module

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开发者_如何学JAVA 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 ...


The get: type within a property descriptor can be used to supply a read-only value that's calculated at runtime:

Object.defineProperty(Array.prototype, 'sayHello', {
    get: function() {
        return "hello I'm an array";
    }
});

Use value: if the property is just a read-only constant value:

Object.defineProperty(Array.prototype, 'sayHello', {
    value: "hello I'm an array"
});

The usage of both of those is just:

var hello = myArray.sayHello;

You should also use the value: type to add a function as a non-enumerable property of a prototype, e.g.:

Object.defineProperty(Array.prototype, 'sayHello', {
    value: function(o) {
        return "hello I'm an array";
    }
});

usage:

var hello = myArray.sayHello();

Likewise,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜