如果安装 colors你会发现你可以像这样编写脚本:
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);
属性的行为怎么可能像函数(如 [5, 6, 4].count
?)。
我理解'Run the trap'.trap()
但不理解'Run the trap'.trap
最佳答案
JavaScript 允许您为 setter 和属性定义 getter(甚至在原型(prototype)上):
Object.defineProperty(Array.prototype, 'count', {
get: function () {
return this.length;
}
});
console.log([1, 2, 3].count);
谨慎使用。颜色,具体来说,uses the non-standard __defineGetter__
function instead , 但效果相同。
关于javascript - 属性如何表现得像函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30464525/