【问题标题】:Calling a method without brackets for Prototype为 Prototype 调用不带括号的方法
【发布时间】:2012-10-05 00:07:54
【问题描述】:

我希望扩展String 类并添加一个简单的方法:

String.prototype.world = function(){
  return " world";
} 

我想做类似的事情:

"hello".world

然后返回"hello world"。而不是这样做:

"hello".world()

调用不带括号的函数将返回函数对象。

我正在寻找的是执行函数而不是返回它(不指定括号)。

我可以用 JavaScript 以某种方式做到这一点吗?

编辑:根据this,使用__defineGetter__ 是非标准且已弃用。寻找替代品。

【问题讨论】:

标签: javascript prototypejs


【解决方案1】:

您可以使用 setter getter 来做到这一点。 jsfiddle。但是 IE

 function getter(){
    return this + " world";
  }
  if(Object.__defineGetter__){ // chrome 
  String.prototype.__defineGetter__('world', getter);
}else{
 Object.defineProperty(String.prototype, 'world', { // IE
                    get : getter
                });
}

【讨论】:

【解决方案2】:

你可以像这样定义一个getter:

String.prototype.__defineGetter__("world", function() {
    return this + ' world';
});

'hello'.world // 'hello world'

fiddle

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2020-08-17
  • 2011-09-28
相关资源
最近更新 更多