javascript - 属性如何表现得像函数?

标签 javascript properties getter

如果安装 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/

相关文章:

javascript - 重置函数时将类移动到第一个兄弟

ios - 忽略的属性和简单的 swift 属性

Pythonic 替代 dict-style setter?

c# - C# expression-bodied 成员的 method 属性

java - 另一个类中的 Get 和 Set 方法

java - 我必须在 Java 中自己的类中使用 getter 方法吗?

javascript - 仅处理 $(this) 元素

javascript - 是否可以从弹出窗口更改 Chrome 扩展程序的设置?

javascript - 找不到模块 : Can't resolve 'firebase' in

c# - 为什么要使用成员变量?