所有属性的JavaScript getter [英] JavaScript getter for all properties

查看:131
本文介绍了所有属性的JavaScript getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说:我处于一种需要PHP风格的getter的情况,但在JavaScript中。



我的JavaScript仅在Firefox中运行,所以Mozilla特定的JS可以通过我。



我唯一能找到一个JS getter的方法需要指定它的名字,但是我想定义一个getter为所有可能的名字。我不知道这是否可能,但我非常想知道。

解决方案

最接近你可以找到是 __noSuchMethod__ ,这是PHP的__call()的等价物。

不幸的是,没有相当于__get / __设置,这是一个耻辱,因为有了它们,我们可以实现__noSuchMethod__,但我还没有看到一种方法来实现属性(在C#中)使用__noSuchMethod __。

  var foo = {
__noSuchMethod__:function(id,args){
alert(id);
alert(args);
}
};

foo.bar(1,2);


Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript.

My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me.

The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for all possible names. I'm not sure if this is possible, but I'd very much like to know.

解决方案

The closest you can find is __noSuchMethod__, which is JavaScript's equivalent of PHP's __call().

Unfortunately, there's no equivalent of __get/__set, which is a shame, because with them we could have implemented __noSuchMethod__, but I don't yet see a way to implement properties (as in C#) using __noSuchMethod__.

var foo = {
    __noSuchMethod__ : function(id, args) {
        alert(id);
        alert(args);
    }
};

foo.bar(1, 2);

这篇关于所有属性的JavaScript getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆