当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Not needing brackets when not passing any arguments

问题描述:

I am creating a function with this line:

window.Spark = window.$ = function(selector, context) { ... };

But I am having a problem (obviously), if I call a function like this $('p').content('Hi!'); then everything works great because I am treating $ like a function. However, when I run a function like this $.ajax('get', 'example.txt'); I get this error $.ajax is not a function. This is because I am not including the brackets. Does anyone know a way around this? I saw in the jQuery source that they have a function within a function. Is this the sort of thing I need?

Thanks for any help you can offer.

网友答案:

I assume by brackets you mean parentheses.

In jQuery, $ is a function with properties.
You can replicate this type of behavior simply by assigning properties to $:

window.Spark = window.$ = function(selector, context) { ... };

$.ajax = function(method, url) { ... };
网友答案:

Functions are first class citizens in JavaScript, i.e. you may treat them like objects are being treated in OOP. It's possible to assign properties to them and those properties may be functions in turn.

So, $.ajax is really nothing else then the property ajax that's a "member" of the function (object) $ that happens to be a function.

So long.

网友答案:

If you put a function within a function it's local to the outer function, so it's not possible to call it from outside the function.

A function in Javascript is an object like any other, so you can add properties to it, and the property can be a function:

var $ = function() { alert("1"); };

$.ajax = function() { alert("2"); };

$(); // shows "1"
$.ajax(); // shows "2"
网友答案:

Um.... $.ajax needs to be a function to be called like that. So either define the 'ajax' function or don't use it.

网友答案:

I'm pretty sure it has nothing to do with "not including the brackets," whatever that means. In jQuery, the identifier $ represents a function object that has several attributes. One of these attributes is ajax, which contains a function that performs an AJAX call. Just because you call your own function $ doesn't mean it automagically gets the functionality of jQuery. If you want $.ajax to be a function, you'll need to define it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: