Possible Duplicate:
If Javascript has first-class functions, why doesn’t this work?
When I try to make an alias function for document.getElementById
as below:
f = document.getElementById;
But, when I try to call:
var e_fullname = f(“fullname”);
It was rised an error: Could not convert JavaScript argument
And below is OK:
var e_fullname = f.call(document, “funname”);
Can you tell me why?
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
The @alias tag causes JSDoc to treat all references to a member as if the member had a different name. This tag is especially useful if you define a class within an inner function; in this case, you can use the @alias tag to tell JSDoc how the class is exposed in your app.
There are four ways of calling a function:
f(p1, p2)
obj.f(p1, p2)
f.apply(obj, [p1, p2])
, f.call(obj, p1, p2)
new f(p1, p2)
In all these cases, f
is just a reference (pointer) to a function object (an object with a [[Call]]
internal property). What makes it behave different in all these cases is the way the function is called, and that matters a lot.
So, f
is just a reference to the getElementById
object, there's no difference between document.getElementById
and someOtherHTMLElement.getElementById
; the function doesn't hold back a reference to the object that references it.
If you want to bind a certain "owner" object, use the bind
method:
var f = document.getElementById.bind(document);
getElementById
is a method on document. To call it, the interpreter needs to have the function body itself, the object to call it on (document in your case), and the arguments.
When you do f = document.getElementById
, you're copying the function body, but not the object to call it on.
When you do this:
f.call(document, “funname”);
You're providing both the object to call it on, and the arguments.
If you want to be able to call f directly, you need to get the "document" object stored in there somehow. Easiest is:
var f = function(name){return document.getElementById(name)}
This creates a closure which holds on the the value of document for you.
You can also use bind() to do the same thing.
You could use bind
Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.
var f = document.getElementById.bind(document);
It was introduced in ES5, so be aware of browsers not yet supporting this version of ECMAScript!
As an alternative you could use the proxy
method of jQuery, added in version 1.4
var f = $.proxy(document.getElementById, document);
Or you could delcare f
as an function of its own (this is a more verbose solution).
var f = function() { return document.getElementById(arguments); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With