调用一个没有括号的函数javascript [英] Invoke a function without parentheses javascript

查看:115
本文介绍了调用一个没有括号的函数javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  String.prototype.addStuff = function( ){
return this.replace(/ / g,-stuff)+-stuff
}

我被告知有一种方法可以在不使用括号的情况下在字符串上调用此函数。
任何人都知道怎么做?



我尝试在括号中包装函数声明并在最后添加一对:

  String.prototype.liu =(function(){
return this.replace(/ / g,-liu)+-liu
})();

但这并不奏效:/ b /

解决方案

您可以使用 Object.defineProperty 并提供一个访问器描述符

  Object.defineProperty(String.prototype,'liu',{
get:function(){
return this.replace(/ / g,-liu)+ -liu
}
});

foo.liu

尽管我不知道你为什么'd想要这样做。


So I wrote this String function to add stuff to each word in a sentence

String.prototype.addStuff = function() {
    return this.replace(/ /g, "-stuff ") + "-stuff"
}

I was told there was a way to invoke this function on a string without using parentheses. Anyone know how?

I tried wrapping the function declaration in parentheses and adding a pair to the end:

String.prototype.liu = (function() {
    return this.replace(/ /g, "-liu ") + "-liu"
})();

But that didn't work :/

解决方案

You can, with Object.defineProperty and providing an accessor descriptor:

Object.defineProperty(String.prototype, 'liu', {
    get: function() {
        return this.replace(/ /g, "-liu ") + "-liu"
    }
});

"foo".liu

Although I don't know why you'd want to do that.

这篇关于调用一个没有括号的函数javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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