在 JavaScript 中调用不带括号的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3929781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:43:50  来源:igfitidea点击:

Calling a function in JavaScript without parentheses

javascript

提问by errorhandler

Is there a way in JavaScript to call a function without parentheses?

JavaScript 中有没有办法在没有括号的情况下调用函数?

For example in jQuery:

例如在 jQuery 中:

$('#wrap').text("asdf");will work and so will $.ajax(ajaxOptions);

$('#wrap').text("asdf");会起作用,所以会 $.ajax(ajaxOptions);

I'm mapping a function (class) to window.$that has a set of functions I want to be able to call with or without parentheses. Like jQuery.

我正在将一个函数(类)映射到window.$具有一组我希望能够使用或不使用括号调用的函数。像 jQuery。

Here's a code example:

这是一个代码示例:

function Test(asdf) {
  this.test = function(testVar) { return testVar + ' asdf'; }
}

And I map Test()to $:

我映射Test()$

window.$ = new Test();

I have to call the function (class) like this:

我必须像这样调用函数(类):

$('asfd').test('ASDF');

But I want to be able to call it like this:

但我希望能够这样称呼它:

$.test('asdf');

采纳答案by mikefrey

You can try something like this

你可以试试这样的

var test = {
    method1 : function(bar) {
        // do stuff here
        alert(bar);
    },
    method2 : function(bar) {
        // do stuff here
        alert(bar);
    }
};

test.method1("foo");
test.method2("fooo");

回答by Anurag

JavaScript is extremely flexible since objects are basically a map and can contain any number of key value pairs, where the value itself can be an object and thus you get nesting. Another interesting aspect of JavaScript is that functions are themselves first class objects, so in a key value pair, you can have a function as a value.

JavaScript 非常灵活,因为对象基本上是一个映射,可以包含任意数量的键值对,其中值本身可以是一个对象,因此您可以嵌套。JavaScript 的另一个有趣的方面是函数本身是第一类对象,因此在键值对中,您可以将函数作为值。

To get something like jQuery then becomes very simple. You start off with a function (constructor function, or class if you will),

获得类似 jQuery 的东西就变得非常简单了。你从一个函数(构造函数,或者类,如果你愿意的话)开始,

function myFunction() {
    // do some awesome web 2.0 stuff
}

Since myfunctionis a function and also an object, so you attach key value pairs to it as well which is what jQuery does. To verify that myFunction is also an object, do an instanceofcheck:

因为它myfunction是一个函数,也是一个对象,所以你也可以将键值对附加到它上面,这就是 jQuery 所做的。要验证 myFunction 也是一个对象,请instanceof检查:

myFunction instanceof Function; // true
myFunction instanceof Object; // true

So we can add properties to a function which could be simple values, or functions themselves.

因此,我们可以向函数添加属性,这些属性可以是简单的值,也可以是函数本身。

// adding a simple property that holds a number
myFunction.firstPrime = 2;

// adding a function itself as a property to myFunction
myFunction.isPrime = function(number) {
    // do some magic to determine if number is prime
};

But if that is not your question, and you really want to know if you can literally call a function without using parentheses, then the answer is yes, you can, using the additions in ECMAScript 5th ed.

但是,如果这不是您的问题,并且您真的想知道是否可以在不使用括号的情况下直接调用函数,那么答案是肯定的,您可以使用 ECMAScript 第 5 版中的添加项。

Here's an example of calling a function without using parentheses using Object.definePropertyand defining it as a getter:

这是使用Object.defineProperty不使用括号调用函数并将其定义为 getter的示例:

var o = {};

Object.defineProperty(o, "helloWorld", {
    get: function() {
        alert("hello world");
    },
    set: undefined
});

o.helloWorld; // will alert "hello world"

Try this examplein Chrome or Safari, or Firefox nightly.

每晚在 Chrome 或 Safari 或 Firefox 中尝试此示例

回答by Dagg Nabbit

new

new



You can call a function using new. The twist is, within the function thisbecomes an object being constructed by the function instead of whatever it would normally be.

您可以使用new. 扭曲的是,在函数内部this变成了一个由函数构造的对象,而不是它通常是的任何东西。

function test () { alert('it worked'); }
...
new test; // alerts "it worked"

calland apply

callapply



You can use callor applyto call a function indirectly. You'll still need parentheses (unless you use new), but you won't be directly invoking the function with parentheses.

您可以使用callapply间接调用函数。您仍然需要括号(除非您使用new),但您不会直接调用带有括号的函数。

回答by Mikhail Nasyrov

function message() {return "Hello crazy world!"; }
Function.prototype.toString = function() { return this.call(this); };
alert(message);

回答by Nick Craver

The difference in those examples is that .text()is a function on jQuery objects (instances of them, wrappers of elements), it's on $.fn(jQuery's prototype shortcut) so it's specifically for jQuery objects.

这些示例中的不同之处在于,它.text()是 jQuery 对象(它们的实例、元素的包装器)上的函数,它位于$.fn(jQuery 的原型快捷方式)上,因此它专门用于 jQuery 对象。

$.ajaxSetup()is a method on the jQueryobject/variable itself.

$.ajaxSetup()jQuery对象/变量本身的方法。

If you look at the APIit's easy to tell which methods are where, the jQuery.something()methods are methods on the jQueryvariable/object, not related to an element set, everything else that's just .something()are the methods to run against element sets (on jQuery object instances).

如果您查看 API,很容易知道哪些方法在哪里,这些jQuery.something()方法是jQuery变量/对象上的方法,与元素集无关,其他一切只是.something()针对元素集运行的方法(在 jQuery 对象实例上) .

For what you want to do, yes it is possible, but it doesn't make much sense, for example:

对于您想做的事情,是的,这是可能的,但这没有多大意义,例如:

$.myFuntion = $.fn.myFunction = function() { alert('hi'); };

You should place your methods where it makes sense, if it's for a set of elements, use $.fn.myFunctionand thisrefers to the set of elements inside. If it's a static method unrelated to an element set place it outside separately or possiblyat $.myFunction.

你应该把你的方法放在有意义的地方,如果它用于一组元素,请使用$.fn.myFunctionthis引用里面的元素集。如果它是与元素集无关的静态方法,则将其单独放置在外部或可能位于$.myFunction.

回答by Ben

You can make a function reference, but you won't be able to pass arguments:

您可以进行函数引用,但不能传递参数:

function funky() { alert("Get down with it"); }

obj.onclick = funky;

回答by Davide Arcinotti

Use template literals:

使用模板文字:

alert`WOW`

It is cleaner and shorter, without having to rely on jQuery, call, etc.

它更简洁更短,无需依赖 jQuery、调用等。