Function.call taking array-like object , doesnt require the first parameter? - javascript

So, I couldn t find out how Function.call doesnt have to take the first argument as an object as I couldn t find such an information anywhere. Although I have seen hundreds of usage of Function.call like the next line of code, taking only this array-like object, NOT REQUIRING THE FIRST PARAMETER AS AN OBJECT, SINCE IT TAKES ARGUMENTS OF FUNCTION WHICH IS AN ARRAY-LIKE OBJECT. It works of course.
argsSliced = Array.prototype.slice.call((function(){return arguments;})(1,2,3,4))
Although next lines of codes behaves as we expect, requiring the first parameter to be an object to set this of function to that object and requires parameters to pass to function after that object.
var a = function(){return arguments[0] + arguments[1] ; }
console.log(a.call(1,2)); // returns NaN
console.log(a.call(null,1,2)); // behaves as we expect, returns 3
So my question, what is the situation with the array-like object ? How does it work with the Function.call as it doesn t give it an object as a first parameter but only gives an array-like object.

This function, when called, returns an array-like Arguments object with the arguments
var f = function(){return arguments;};
Then, when you call it with arguments 1,2,3 and 4,
f(1,2,3,4) // Arguments [1,2,3,4]
Then, you call Function.prototype.call on Array.prototype.slice, passing that Arguments object as the argument.
So Function.prototype.call will call Array.prototype.slice with the this value set to the Arguments object (instead of Array.prototype), and no arguments.
When Array.prototype.slice is called on an array-like object, it builds a real array from that object. So you get
Array.prototype.slice.call(f(1,2,3,4)); // Array [1,2,3,4]
Note there are better ways to achieve this:
Array.of(1,2,3,4)
Array(1,2,3,4)
[1,2,3,4]

MDN for call() explains it clearly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
The value of this provided for the call to function. Note that this may not
be the actual value seen by the method: if the method is a function in
non-strict mode code, null and undefined will be replaced with the
global object and primitive values will be converted to objects.
var a = function(){return arguments[0] + arguments[1] ; }
console.log(a.call(1,2));
arguments[1] will be undefined ,and 2 will be arguments[0] because 1 will be boxed to an object.
remember f.call(ob,4); is like saying ob.f(4)

Related

Why Object and Array constructor don't need to be prefixed with new for constructing an object?

Consider the following snippet :-
function Custom(){}
// prints {}
console.log(Object());
// prints []
console.log(Array());
// prints undefined
console.log(Custom())
// prints {}
console.log(new Custom());
I know that the Custom function constructor needs a new keyword prefixed to bind this. Why isn't that necessary for Array and Object constructors ?
The array constructor says:
also creates and initializes a new Array object when called as a function rather than as a constructor. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
The object constructor says:
If NewTarget is neither undefined nor the active function, then
a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").
If value is undefined or null, return ! OrdinaryObjectCreate(%Object.prototype%).
Return ! ToObject(value).
So it's explicitly noted that new isn't required for either of those.
(though, you should probably never be using either Object or Array as constructors, whether with or without new - better to use object and array literals)
It'll be trivial to implement this sort of thing yourself in Custom, if you want - check if the function was called with new, and if not, explicitly return something:
function Custom(){
if (!new.target) {
return new Custom();
}
}
console.log(Custom())
console.log(new Custom());
Custom, Object, and Array all are functions. When you call them, i.e. Object(), the value printed is the return value of the function. Object and Array returns a new empty object and array respectively. While the Custom function returns nothing and thus undefined is printed.
When you call a function with new is creates an object by calling the function as a constructor. As one of the comments mentioned This gives more details about the new keyword.

Changing JavaScript function's parameter value using arguments array not working

I am learning JavaScript and am pretty confused about the arguments property array.
I have a function that takes a single argument and returns it. When I pass the parameter and reassign it using arguments[0] = value, it's updating the value.
function a(b) {
arguments[0] = 2;
return b;
}
console.log(a(1)); //returns 2
But when I call the same function with no parameters it returns undefined.
function a(b) {
arguments[0] = 2;
return b;
}
console.log(a()); //returns undefined
But even if I pass undefined, the value will update as well.
function a(b) {
arguments[0] = 2;
return b;
}
console.log(a(undefined)); //returns 2
I thought that if you do not pass a parameter to a JavaScript function, it automatically creates it and assigns the value to undefined and after updating it should reflect the updated value, right?
Also a() and a(undefined) are the same thing, right?
Assigning to arguments indicies will only change the associated argument value (let's call it the n-th argument) if the function was called with at least n arguments. The arguments object's numeric-indexed properties are essentially setters (and getters):
http://es5.github.io/#x10.6
Italics in the below are my comments on how the process relates to the question:
(Let) args (be) the actual arguments passed to the [[Call]] internal method
Let len be the number of elements in args.
Let indx = len - 1.
Repeat while indx >= 0, (so, the below loop will not run when no arguments are passed to the function:)
(assign to the arguments object being created, here called map:)
Add name as an element of the list mappedNames.
Let g be the result of calling the MakeArgGetter abstract operation with arguments name and env.
Let p be the result of calling the MakeArgSetter abstract operation with arguments name and env.
Call the [[DefineOwnProperty]] internal method of map passing ToString(indx), the Property Descriptor {[[Set]]: p, [[Get]]: g, [[Configurable]]: true}, and false as arguments.
So, if the function is invoked with no arguments, there will not be a setter on arguments[0], so reassigning it won't change the parameter at index 0.
The same sort of thing occurs for other indicies as well - if you invoke a function with 1 parameter, but the function accepts two parameters, assigning to arguments[1] will not change the second parameter, because arguments[1] does not have a setter:
function fn(a, b) {
arguments[1] = 'bar';
console.log(b);
}
fn('foo');
So
a() and a(undefined) are the same thing right?
is not the case, because the second results in an arguments object with a setter and a getter on index 0, while the first doesn't.
Note that this odd interaction between the arguments and the function parameters is only present in sloppy mode. In strict mode, changes to arguments won't have any effect on the value an individual argument identifier contains:
'use strict';
function a(b) {
arguments[0] = 2;
return b;
}
console.log(a(1)); //returns 1
ECMA 262 9.0 2018 describes this behaviour in 9.4.4 Arguments Exotic Objects with
NOTE 1:
The integer-indexed data properties of an arguments exotic object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function's execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. If the arguments object is an ordinary object, the values of its properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
In short,
if in 'sloppy mode', then all arguments are mapped to their named variables, if the length correspond to the given parameter, or
if in 'strict mode', then the binding is lost after handing over the arguments.
This is only readable in an older version of ECMA 262 7.0 2016. It describes this behaviour in 9.4.4 Arguments Exotic Objects with
Note 1:
For non-strict functions the integer indexed data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function's execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object's properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
it's because arguments it's not like a Array, it's a object with integer indexed data keys, and property length, And if length equal zero it's mean you don't have a arguments
function a(b) {
arguments[0] = 2;
console.log(arguments.length)
return b;
}
a(1); // length 1 returns 2
console.log(a()); // length 0 returns undefined
When you are not providing any parameter then arguments array has length equal to 0. Then you are trying to set the non existing element of array to 2 which causes returning undefined
You can simply test this with this snippet:
function a(b){
alert(arguments.length) // It will prompt 0 when calling a() and 1 when calling a(undefined)
arguments[0] = 2;
return b;
}
This is the undefined value definition from javascript spec :
primitive value used when a variable has not been assigned a value.
so if you do not specify the function return type it will return undefined.
so a() and a(undefined) it is not same thing. returning undefined is based on return type is defined or not.
for more clarification similar_problem
My understanding is that the arguments object only tracks what is passed into the function. Since you've not initially passed anything, b is not bound and at that point arguments is not 'tracking' b. Next, you assign a value to the initialised but empty Array-like object arguments and finally return b, which is undefined.
To delve into this further:
If a non-strict function does not contain rest, default, or destructured parameters, then the values in the arguments object do change in sync with the values of the argument variables. See the code below:
function func(a) {
arguments[0] = 99; // updating arguments[0] also updates a
console.log(a);
}
func(10); // 99
and
function func(a) {
a = 99; // updating a also updates arguments[0]
console.log(arguments[0]);
}
func(10); // 99
When a non-strict function does contain rest, default, or destructured parameters, then the values in the arguments object do not track the values of the arguments. Instead, they reflect the arguments provided when the function was called:
function func(a = 55) {
arguments[0] = 99; // updating arguments[0] does not also update a
console.log(a);
}
func(10); // 10
and
function func(a = 55) {
a = 99; // updating a does not also update arguments[0]
console.log(arguments[0]);
}
func(10); // 10
and
// An untracked default parameter
function func(a = 55) {
console.log(arguments[0]);
}
func(); // undefined
Source: MDN Web docs

JavaScript apply giving strange output for String prototype calls

When calling String.prototype functions with an array of arguments, I am getting unexpected behavior.
'foo'.concat.apply(this, ['bar','faz']);
//actual=> [object global]barfaz
//expected=> foobarfaz
'foo'.repeat.apply(this, [3]);
//actual=> [object global][object global][object global]
//expected=> foofoofoo
I am only receiving these issues for prototype function calls which have arguments that I am calling apply with:
'FOO'.toLowerCase();
//actual & expected=> foo
I have tried to manually pass in the parameters without apply, but in my final code I need to apply an array to the parameters, so there seems to be no way around apply.
the problem is that this is resolve when called, not when it's accessed inside the method. In this case, this is resolving to the global object. Also, the object these methods are called on become irrelevant, because the first argument to apply sets the this value in the method.
Instead pass the string as the first argument.
String.prototype.concat.apply('foo', ['bar','faz']);
String.prototype.repeat.apply('foo', [3]);
Alternate way of doing this:
''.concat.apply('foo', ['bar','faz']);
''.repeat.apply('foo', [3]);
Why so complicated?
var a = "foo", b = ["bar", "baz"];
a + b.join("");
or as a function
//a utility
function string(v){ return v == null? "": String(v) };
function stringconcat(a,b){
return (Array.isArray(a)? a.join(""): string(a))+
(Array.isArray(b)? b.join(""): string(b))
}

Is it safe to pass 'arguments' to 'apply()'

Suppose I have the following code (completely useless, I know)
function add( a, b, c, d ) {
alert(a+b+c+d);
}
function proxy() {
add.apply(window, arguments);
}
proxy(1,2,3,4);
Basically, we know that apply expects an array as the second parameter, but we also know that arguments is not a proper array. The code works as expected, so is it safe to say that I can pass any array-like object as the second parameter in apply()?
The following will also work (in Chrome at least):
function proxy() {
add.apply(window, {
0: arguments[0],
1: arguments[1],
2: arguments[2],
3: arguments[3],
length: 4
});
}
Update: It seems that my second code block fails in IE<9 while the first one (passing arguments) works.
The error is Array or arguments object expected, so we shall conclude that it's always safe to pass arguments, while it's not safe to pass an array-like object in oldIE.
From definition of Function.prototype.apply in MDN:
fun.apply(thisArg[, argsArray])
You can also use arguments for the argsArray parameter. arguments is a
local variable of a function. It can be used for all unspecified
arguments of the called object. Thus, you do not have to know the
arguments of the called object when you use the apply method. You can
use arguments to pass all the arguments to the called object. The
called object is then responsible for handling the arguments.
REF: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply
As the second argument apply accepts "an array like object, specifying the arguments with which function should be called". To my understanding, this array-like object should have the length property for internal iteration, and numerically defined properties (zero-indexed) to access the values.
And the same is confirmed my the spec: http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.3, as was kindly pointed out by #Pointy.
Assuming ECMAScript 5.1: Yes. As per ECMA-262, 10.6, the arguments object has the length and index properties that 15.3.4.3 (Function.prototype.apply) requires.
MDN can only speak for Mozilla implementations. The actual spec to which all implementations should comply says the following:
15.3.4.3 Function.prototype.apply (thisArg, argArray)
When the apply method is called on an object func with arguments thisArg and
argArray, the following steps are taken:
1. If IsCallable(func) is false, then throw a TypeError exception.
2. If argArray is null or undefined, then
Return the result of calling the [[Call]] internal method of func,
providing thisArg as the this value and an empty list of arguments.
3. If Type(argArray) is not Object, then throw a TypeError exception.
4. Let len be the result of calling the [[Get]] internal method of argArray
with argument "length".
5. If len is null or undefined, then throw a TypeError exception.
6. Let n be ToUint32(len).
7. If n is not equal to ToNumber(len), then throw a TypeError exception.
8. Let argList be an empty List.
9. Let index be 0.
10. Repeat while index < n
a. Let indexName be ToString(index).
b. Let nextArg be the result of calling the [[Get]] internal method of
argArray with indexName as the argument.
c. Append nextArg as the last element of argList.
d. Set index to index + 1.
11. Return the result of calling the [[Call]] internal method of func,
providing thisArg as the this value and argList as the list of arguments.
The length property of the apply method is 2.
NOTE The thisArg value is passed without modification as the this value. This
is a change from Edition 3, where an undefined or null thisArg is replaced
with the global object and ToObject is applied to all other values and that
result is passed as the this value.
It seems that property length and numeric index values are the only prerequisites.

What is the .call() function doing in this Javascript statement?

I'm actively learning javascript, and I came across the following statement:
Object.prototype.toString.call([]);
And I don't know what it means or what it does.
I have a vague understanding of .call, in that it allows you to call a method in the context of a different object (I think), but I am having a hard time understanding what role the .call() function is playing in the above statement. So I was wondering if anyone could explain what .call() is doing here?
Thanks!!
The call method sets the this value of the invoked function to the object passed as first argument, in your example, you are executing the Object.prototype.toString method on an Array object.
Array objects, have their own toString method (Array.prototype.toString) that shadows the one from Object.prototype, if you call [].toString(); the method on the Array.prototype will be invoked.
For example:
function test() {
alert(this);
}
test.call("Hello"); // alerts "Hello"
Another example:
var alice = {
firstName: 'Alice',
lastName: 'Foo',
getName: function () {
return this.firstName + ' ' + this.lastName;
}
};
var bob = {
firstName: 'Bob',
lastName: 'Bar',
};
alice.getName.call(bob); // "Bob Bar"
In the above example, we use the Alice's getName method on the Bob's object, the this value points to bob, so the method works just as if it were defined on the second object.
Now let's talk about the Object.prototype.toString method. All native objects in JavaScript contain an internal property called [[Class]] this property contains a string value that represents the specification defined classification of an object, the possible values for native objects are:
"Object"
"Array"
"Function"
"Date"
"RegExp"
"String"
"Number"
"Boolean"
"Error" for error objects such as instances of ReferenceError, TypeError, SyntaxError, Error, etc
"Math" for the global Math object
"JSON" for the global JSON object defined on the ECMAScript 5th Ed. spec.
"Arguments" for the arguments object (also introduced on the ES5 spec.)
"null" (introduced just a couple of days ago in the ES5 errata)
"undefined"
As I've said before that property is internal, there is no way to change it, the specification doesn't provide any operator or built-in function to do it, and the only way you can access its value is through the Object.prototype.toString method.
This method returns a string formed by:
"[object " + this.[[Class]] + "]"
Only for expository purposes because [[Class]] cannot be accessed directly.
For example:
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(/foo/); // "[object RegExp]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call(new Date); // "[object Date]"
// etc...
This is really useful to detect the kind of an object in a safe way, for detecting array objects, it's the most widely used technique:
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
It might be tempting to use the instanceof operator, but that way will lead to problems if you work on cross-frame environments, because an array object created on one frame, will not be instanceof the Array constructor of another.
The above method will work without any problems, because the object will contain the value of its [[Class]] internal property intact.
See also:
instanceof considered harmful (or how to write a robust isArray)
Object.prototype.toString
Object Internal Properties and Methods
Because toString is mostly not invoked with a parameter, not toString('foo'), but bar.toString(). Which is where call comes in handy.
Different toStrings
I say "mostly" because there are different toStrings:
Object.prototype.toString returns a string representing object
Array.prototype.toString returns a string representing the specified array and its elements
Number.prototype.toString returns a string representing the specified Number object
String.prototype.toString returns a string representing the specified String object
Function.prototype.toString returns a string representing the source code of the function
Instance of Uses Separately
(new Object()).toString(); // "[object Object]"
["foo", "bar"].toString(); // "foo,bar"
(6).toString(2); // "110"
("meow").toString(); // "meow"
(function(){return 'x';}).toString() // "function (){return 'x';}"
Though all object prototypically inherit from Object, the latter ones don't inherit toString from Object's toString, which means that they're all different things and have different uses. To tell the type of an object, Object.prototype.toString is the useful one, since it returns a type:
Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type.
Call
Note that among them the only one that takes parameter is Number.prototype.toString, and it's for specifying base of the outcome number. Therefore, in order to invoke Object.prototype.toString for arrays, numbers and other object that has their own toString method, you need call to specify this:
Object.prototype.toString.call(Math); // [object Math]
Object.prototype.toString.call(new Date); // [object Date]
Object.prototype.toString.call(new String); // [object String]
Object.prototype.toString.call(Math); // [object Math]
// Since JavaScript 1.8.5
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]

Categories

Resources