JavaScript 相当于 Perl 的 AUTOLOAD
我想我可能会在谷歌搜索中失败,也许这种模式不适合 JavaScript 处理 MRO 的方式,但我正在寻找与 Perl 的 AUTOLOAD 方法等效的方法,这样:
function car() {
return {
start: function() { alert('vrooom') },
catchall: function() { alert('car does not do that'); }
}
};
car().start(); //vrooom
car().growBeard(); //car does not do that
在 Perl 中快速处理这种情况我会写:
sub AUTOLOAD { __PACKAGE__." doesn't do that" }
但是我无法理解 JavaScript 中捕获未定义方法的语法。 也许重载 .call 或 .apply 之类的?
I think I might fail at Googling, and maybe this pattern just doesn't fit with the way JavaScript handles MRO, but I'm looking for an equivalent to Perl's AUTOLOAD method such that:
function car() {
return {
start: function() { alert('vrooom') },
catchall: function() { alert('car does not do that'); }
}
};
car().start(); //vrooom
car().growBeard(); //car does not do that
in Perl to quickly handle this situation I'd write:
sub AUTOLOAD { __PACKAGE__." doesn't do that" }
but the syntax to catch an undefined method in JavaScript eludes me.
Perhaps overloading .call or .apply or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只是想知道是否定义了某个方法,您可以执行以下操作:
听起来您要找的是
__noSuchMethod__
,但是它仅在 mozilla 中受支持,而不是正式 ECMAScript 规范的一部分。jsfiddle 上的
__noSuchMethod__
示例,仅适用于基于 mozilla 的浏览器。使用简单的异常处理,您也许能够获得所需的行为:
If you simply want to know if a method is defined you can do the following:
It sounds like what you are looking for is
__noSuchMethod__
, however it is only supported in mozilla, and not part of the formal ECMAScript specifications.Example of
__noSuchMethod__
on jsfiddle, only works in a mozilla based browser.Using simple exception handling you might be able to get your desired behavior:
新的 ES6 代理对象将有所帮助:(从此处复制的示例代码)
代理对象是不可调整的。浏览器支持很好,但还不完美,请参阅 http://caniuse.com/#feat=proxy。
The newish ES6 Proxy object will help: (sample code copied from here)
Proxy objects are unshimmable. Browser support is good, but not perfect yet, see http://caniuse.com/#feat=proxy.