【问题标题】:Method missing in JS [duplicate]JS中缺少方法[重复]
【发布时间】:2014-05-13 09:42:57
【问题描述】:

在 python 中我可以这样做:

class Converter(object):
    def __init__(self, amount):
        self.amount = amount

    def rupy(self):
        return self.amount * 2

    def __getattr__(self, *args, **kwargs):
        if args[0] == 'rupies':
            return self.rupy

JS 是否提供了某种方式来实现相同的行为?我用谷歌搜索了一下,找到了关于 noSuchMethod 的文章,但它只适用于 Firefox。

编辑:我不想有别名我想有一种方法来处理一般缺失的方法

【问题讨论】:

标签: javascript prototypal-inheritance


【解决方案1】:

简答

JavaScript 是否与 __getattr__ 等效?

没有:(


长答案

看起来你只是想映射别名,JavaScript 给这样的东西添加属性没有问题

// set up
function Converter(amount) {
    this.amount = amount;
}
Converter.prototype.rupy = function () {
    return this.amount * 2;
};
// add aliases
var original = 'rupy', aliases = ['rupies'], i;
for (i = 0; i < aliases.length; ++i)
    Converter.prototype[aliases[i]] = Converter.prototype[original];

现在

var foo = new Converter(1);
foo.rupies(); // 2

并且拥有

foo.rupies === foo.rupy; // true

未来的答案

ECMAScript 6 (Harmony) 我们有 Proxies

Constructor.prototype = Proxy(Constructor.prototype, {
    'get': function (target, name, child) {
            var o = child || target; /* =proxy? if proxy not inherited? */
            if (name in target) return o[name];
            if (name === 'rupies') return o['rupy'];
            return;
        },
    'set': function (target, name, val, child) {
            return target[name] = val;
        },
    'has': function (target, name) {
            return name in target; // do you want to make 'rupies' visible?
        },
    'enumerate': function (target) {
            for (var key in target) yield key;
        }
});

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 2020-03-24
    • 1970-01-01
    • 2014-06-06
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多