长话短说:我的情况是我喜欢PHP式的getter,但是在JavaScript中.
我的JavaScript只在Firefox中运行,因此我可以使用Mozilla特定的JS.
我可以找到制作JS getter的唯一方法是需要指定它的名称,但是我想为所有可能的名称定义一个getter .我不确定这是否可行,但我非常想知道.
在一些javascript实现中有一个noSuchMethod功能(Rhino,SpiderMonkey)
proxy = {
__noSuchMethod__: function(methodName, args){
return "The " + methodName + " method isn't implemented yet. HINT: I accept cash and beer bribes" ;
},
realMethod: function(){
return "implemented" ;
}
}
js> proxy.realMethod()
implemented
js> proxy.newIPod()
The newIPod method isn't implemented yet. HINT: I accept cash and beer bribes
js>
Run Code Online (Sandbox Code Playgroud)
我想知道,有没有办法为房产做类似的事情?我想编写可以在属性和方法上分派的代理类.
有没有办法__getattr__
在Javascript中模拟Python的方法?
我想拦截Javascript对象属性的'获取'和'集'.
在Python中,我可以编写以下内容:
class A:
def __getattr__(self, key):
return key
a = A()
print( a.b ) # Output: b
Run Code Online (Sandbox Code Playgroud)
Javascript怎么样?
如果情况并非如此,那对我来说是有意义的,因为它可能会导致编译器错误.
__call()
在对象上下文中调用不可访问的方法时触发.
可能重复:
所有属性的JavaScript getter
JavaScript是否提供了访问未定义对象属性的方法?在PHP中,解决方案是__get()
在类中声明和实现方法.
使用try { .. } catch { .. }
的解决方案对我来说还不够,因为我已经拥有非常大量的代码,而这些代码实际上需要保持原样.
我想知道是否有一种方法可以模仿 Node.js 中 PHP 的神奇方法 __get() 和 __set()。从这个问题:JavaScript getter for allproperty我知道你可以在Rhino中做到这一点,但Node是建立在V8之上的。V8有办法做到这一点吗?
我有以下代码,其中我使用代理对象(代理)来尝试捕获方法调用和属性访问:
示例: https: //jsfiddle.net/r8j4fzxL/2/
(function() {
'use strict';
console.clear();
//some empty class where I want to trap methods props
class X {
//...
}
let proxy = {
get: function(target, prop, receiver) {
console.log('get called: ',
'target:', target,
'prop:', prop,
'receiver:', receiver
);
//this is OK, if we are called as a method.
//but it isn't when called as .prop - because, obviously, we return a function here.
return function(...args) {
console.log('wrapper args:', args);
return 42;
}
},
};
let …
Run Code Online (Sandbox Code Playgroud) javascript ×6
php ×3
ecmascript-6 ×1
firefox ×1
get ×1
getter ×1
java ×1
node.js ×1
properties ×1
undefined ×1
v8 ×1