How do properties act as functions?

If you set colors , you will see that you can write scripts as follows:

var colors = require('colors');

console.log('hello'.green);
console.log('i like cake and pies'.underline.red)
console.log('inverse the color'.inverse);
console.log('OMG Rainbows!'.rainbow);
console.log('Run the trap'.trap);

How is it possible that properties behave like functions (e.g. [5, 6, 4].count?).

I understand 'Run the trap'.trap(), but not'Run the trap'.trap

+4
source share
2 answers

JavaScript allows you to define getters for setters and properties (even on prototypes):

Object.defineProperty(Array.prototype, 'count', {
    get: function () {
        return this.length;
    }
});

console.log([1, 2, 3].count);

Use sparingly. colors, in particular, instead uses a non-standard __defineGetter__function , but with the same effect.

+5
source

This can be achieved with getters :

Object.defineProperty(String.prototype, "testing", {
    get: function() {
        return this.string + ' some test message ';
    }
});
console.log( 'my string'.testing ); // my string some test message
+1
source

All Articles