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

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]

Related

How to Show the API's data when i choose its class through an <input> [duplicate]

I am trying to alert a returned value from a function and I get this in the alert:
[object Object]
Here is the JavaScript code:
<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible());
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
</script>
whichIsVisible is the function which I am trying to check on.
As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?
That is because there are different types of objects in Javascript!
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
… several more …
and Object objects!
stringify({}) -> [object Object]
That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
The default conversion from an object to string is "[object Object]".
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.
Sidenote: IDs should not start with digits.
[object Object] is the default toString representation of an object in javascript.
If you want to know the properties of your object, just foreach over it like this:
for(var property in obj) {
alert(property + "=" + obj[property]);
}
In your particular case, you are getting a jQuery object. Try doing this instead:
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible().attr("id"));
});
This should alert the id of the visible element.
You can see value inside [object Object] like this
Alert.alert( JSON.stringify(userDate) );
Try like this
realm.write(() => {
const userFormData = realm.create('User',{
user_email: value.username,
user_password: value.password,
});
});
const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
Alert.alert( JSON.stringify(userDate) );
reference
https://off.tokyo/blog/react-native-object-object/
Basics
You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.
string, number, boolean, null, undefined, and symbol.
In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
If primitives have no properties, why does "this is a string".length return a value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
By this means primitives have access to all the properties (including methods) defined by their respective object constructors.
So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.
Analysis of toString() method
Consider the following code
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.
But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?
Closer look at Object.prototype.toString()
As per the documentation,
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Understand this from the following example
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
References:
https://es5.github.io/x15.2.html#x15.2.4.2
https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
It's the value returned by that object's toString() function.
I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:
function whichIsVisible_v2()
{
if (!$1.is(':hidden')) return '#1';
if (!$2.is(':hidden')) return '#2';
}
That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.
[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
I think the best way out is by using JSON.stringify() and passing your data as param:
alert(JSON.stringify(whichIsVisible()));
You have a javascript object
$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...
you have to treat $1 and $2 like jQuery objects.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".
Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.
The object whose class is Object seems quite different from the usual class instance object, because it acts like an associative array or list: it can be created by simple object literals (a list of keys and properties), like this: let obj={A:'a',B:'b'}; and because it looks very like this same literal notation when displayed in the Developer Tools Console pane and when it is converted to a JSON string.
But, in fact, the only real difference in objects of other classes (which are derived or extended from Object) is that other classes usually have constructors and methods (these are all functions), in addition to properties (which are variables). A class instance object is allocated using the 'new' operator, and its properties and methods are accessible through the 'this' variable. You can also access the underlying static functions that are copied to each new instance by using the 'prototype' property, and even extend system classes by adding new functions to their prototype object.
The Array object is also derived from Object and is frequently used: it is an ordered, 0-indexed array of variable values.
Object objects, unlike Arrays and other classes are treated simply as associative arrays (sometimes considered ordered, and sometimes considered unordered).

How to fetch key and value from javascript object using Object.entries? [duplicate]

I am trying to alert a returned value from a function and I get this in the alert:
[object Object]
Here is the JavaScript code:
<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible());
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
</script>
whichIsVisible is the function which I am trying to check on.
As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?
That is because there are different types of objects in Javascript!
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
… several more …
and Object objects!
stringify({}) -> [object Object]
That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
The default conversion from an object to string is "[object Object]".
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.
Sidenote: IDs should not start with digits.
[object Object] is the default toString representation of an object in javascript.
If you want to know the properties of your object, just foreach over it like this:
for(var property in obj) {
alert(property + "=" + obj[property]);
}
In your particular case, you are getting a jQuery object. Try doing this instead:
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible().attr("id"));
});
This should alert the id of the visible element.
You can see value inside [object Object] like this
Alert.alert( JSON.stringify(userDate) );
Try like this
realm.write(() => {
const userFormData = realm.create('User',{
user_email: value.username,
user_password: value.password,
});
});
const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
Alert.alert( JSON.stringify(userDate) );
reference
https://off.tokyo/blog/react-native-object-object/
Basics
You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.
string, number, boolean, null, undefined, and symbol.
In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
If primitives have no properties, why does "this is a string".length return a value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
By this means primitives have access to all the properties (including methods) defined by their respective object constructors.
So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.
Analysis of toString() method
Consider the following code
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.
But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?
Closer look at Object.prototype.toString()
As per the documentation,
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Understand this from the following example
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
References:
https://es5.github.io/x15.2.html#x15.2.4.2
https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
It's the value returned by that object's toString() function.
I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:
function whichIsVisible_v2()
{
if (!$1.is(':hidden')) return '#1';
if (!$2.is(':hidden')) return '#2';
}
That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.
[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
I think the best way out is by using JSON.stringify() and passing your data as param:
alert(JSON.stringify(whichIsVisible()));
You have a javascript object
$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...
you have to treat $1 and $2 like jQuery objects.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".
Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.
The object whose class is Object seems quite different from the usual class instance object, because it acts like an associative array or list: it can be created by simple object literals (a list of keys and properties), like this: let obj={A:'a',B:'b'}; and because it looks very like this same literal notation when displayed in the Developer Tools Console pane and when it is converted to a JSON string.
But, in fact, the only real difference in objects of other classes (which are derived or extended from Object) is that other classes usually have constructors and methods (these are all functions), in addition to properties (which are variables). A class instance object is allocated using the 'new' operator, and its properties and methods are accessible through the 'this' variable. You can also access the underlying static functions that are copied to each new instance by using the 'prototype' property, and even extend system classes by adding new functions to their prototype object.
The Array object is also derived from Object and is frequently used: it is an ordered, 0-indexed array of variable values.
Object objects, unlike Arrays and other classes are treated simply as associative arrays (sometimes considered ordered, and sometimes considered unordered).

How to Pass object to url parameter and then get it [duplicate]

I am trying to alert a returned value from a function and I get this in the alert:
[object Object]
Here is the JavaScript code:
<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible());
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
</script>
whichIsVisible is the function which I am trying to check on.
As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?
That is because there are different types of objects in Javascript!
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
… several more …
and Object objects!
stringify({}) -> [object Object]
That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
The default conversion from an object to string is "[object Object]".
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.
Sidenote: IDs should not start with digits.
[object Object] is the default toString representation of an object in javascript.
If you want to know the properties of your object, just foreach over it like this:
for(var property in obj) {
alert(property + "=" + obj[property]);
}
In your particular case, you are getting a jQuery object. Try doing this instead:
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible().attr("id"));
});
This should alert the id of the visible element.
You can see value inside [object Object] like this
Alert.alert( JSON.stringify(userDate) );
Try like this
realm.write(() => {
const userFormData = realm.create('User',{
user_email: value.username,
user_password: value.password,
});
});
const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
Alert.alert( JSON.stringify(userDate) );
reference
https://off.tokyo/blog/react-native-object-object/
Basics
You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.
string, number, boolean, null, undefined, and symbol.
In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
If primitives have no properties, why does "this is a string".length return a value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
By this means primitives have access to all the properties (including methods) defined by their respective object constructors.
So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.
Analysis of toString() method
Consider the following code
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.
But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?
Closer look at Object.prototype.toString()
As per the documentation,
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Understand this from the following example
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
References:
https://es5.github.io/x15.2.html#x15.2.4.2
https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
It's the value returned by that object's toString() function.
I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:
function whichIsVisible_v2()
{
if (!$1.is(':hidden')) return '#1';
if (!$2.is(':hidden')) return '#2';
}
That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.
[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
I think the best way out is by using JSON.stringify() and passing your data as param:
alert(JSON.stringify(whichIsVisible()));
You have a javascript object
$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...
you have to treat $1 and $2 like jQuery objects.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".
Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.
The object whose class is Object seems quite different from the usual class instance object, because it acts like an associative array or list: it can be created by simple object literals (a list of keys and properties), like this: let obj={A:'a',B:'b'}; and because it looks very like this same literal notation when displayed in the Developer Tools Console pane and when it is converted to a JSON string.
But, in fact, the only real difference in objects of other classes (which are derived or extended from Object) is that other classes usually have constructors and methods (these are all functions), in addition to properties (which are variables). A class instance object is allocated using the 'new' operator, and its properties and methods are accessible through the 'this' variable. You can also access the underlying static functions that are copied to each new instance by using the 'prototype' property, and even extend system classes by adding new functions to their prototype object.
The Array object is also derived from Object and is frequently used: it is an ordered, 0-indexed array of variable values.
Object objects, unlike Arrays and other classes are treated simply as associative arrays (sometimes considered ordered, and sometimes considered unordered).

Why Math.toString() return [object Math]?

I read here that :
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.
So: result this code, must be [object object ] because typeof Math is object but , i see result is [object Math]
var toString = Object.prototype.toString;
console.log( toString.call(Math) ) ;
var toString = Object.prototype.toString;
console.log( toString.call(Math) ) ;
Tahnkyou!
The relevant parts within the specs are:
20.2.1.9 Math [ ##toStringTag ]:
The initial value of the ##toStringTag property is the String value "Math".
This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
19.1.3.6 Object.prototype.toString ( ):
Historically, this function was occasionally used to access the String value of the [[Class]] internal slot that was used in previous editions of this specification as a nominal type tag for various built-in objects. The above definition of toString preserves compatibility for legacy code that uses toString as a test for those specific kinds of built-in objects. It does not provide a reliable type testing mechanism for other kinds of built-in or program defined objects. In addition, programs can use ##toStringTag in ways that will invalidate the reliability of such legacy type tests.
So with the current specs the result of toString will be [object ##toStringTag].
In earlier versions it was defined as :
15.8 The Math Object
The value of the [[Class]] internal property of the Math object is "Math".
15.2.4.2 Object.prototype.toString ( )
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
What you are getting is exactly what is described and expected:
toString() can be used with every object and allows you to get its class.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString#Using_toString()_to_detect_object_class
Your answer lies here:
toString() can be used with every object and allows you to get its
class. To use the Object.prototype.toString() with every object, you
need to call Function.prototype.call() or
Function.prototype.apply() on it, passing the object you want to
inspect as the first parameter called thisArg.
Meaning when you preform:
var toString = Object.prototype.toString;
console.log(toString.call(Math));
You are getting and printing the class - object Math.
taken from developer.mozilla.

Is Function really an Object

I am a self taught web developer and am still trying to come to grips with some JavaScript fundamentals. Below are some quotes extracted from Douglas Crockford's Good Parts.
"Functions in JavaScript are Objects"
"In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects"
"Every object is linked to a prototype object from which it can inherit properties" (namely constructor, toString, ...)
If Function is an Object then why
console.log(typeof Function); // function
is its type a function and not object
console.log(Object.constructor); // Function()
is it the constructor of its 'parent'
console.log(Function.constructor); // Function()
puzzled so the constructor is in-fact a function?
console.log(typeof Function.prototype); // Function
is the type of its prototype a function and not an object? i thought it inherited from Object
Answers to these questions will greatly assist my understanding on JavaScript.
If Function is an Object then why is its type a function and not object?
Because the typeof operator is defined like that, probably for usability:
Object (native and does not implement [[Call]]) returns "object"
Object (native or host and does implement [[Call]]) returns "function"
Object (host and does not implement [[Call]])
returns an Implementation-defined value that may not be "undefined", "boolean", "number", or "string".
[[Call]] is an internal property of an object that identifies the object as a function (callable). A non-native object is an object provided by the host (e.g. browser), such as a DOM object or an instance of ActiveXObject.
puzzled so the constructor is in-fact a function?
Why wouldn't it be? Constructors are functions. Instances can only be constructed using functions. Object.constructor is a function, but it's also an object. See the following:
console.log((function () { }) instanceof Object);
//-> true
Also, from the ECMAScript speficiation:
Every built-in function and every built-in constructor has the Function prototype object, which is the initial value of the expression Function.prototype (15.3.4), as the value of its [[Prototype]] internal property.
Unless otherwise specified every built-in prototype object has the Object prototype object, which is the initial value of the expression Object.prototype (15.2.4), as the value of its [[Prototype]] internal property, except the Object prototype object itself.
And also, to answer your final puzzlement:
The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined.
When we say, "a function is an object", we don't mean "is" as in "instead of", we mean it in the same sense as "a cat is an animal". If someone asked you what kind of pet you had, you wouldn't answer "an animal". typeof would be useless if it always responded object.
A function is an object, but that's not an interesting thing for typeof to return, since it's a static quality of the language itself, not something that needs to be reported at runtime.
The typeof operator would be quite useless if it always returned "object", wouldn't it? Everything is an object, but it can be other things too. For example, a string is an object, but it is also a string :) The operator returns the name of the most specific type so to speak, not the most generic one. That should explain why typeof Functionis "function".
As for the constructor property, the constructor is a function that is invoked by the operator new when an object is created. It is always a function, regardless of whether the object itself is Object, Functionor something else.
The console.log(typeof Function); shows that the object is of type Function and not object.
To give you an example:
function squareValue(var x) {
return x * x;
}
can be loosely translated as
var squareValue = new Function("x", "return x*x");
and thus, doing
var valueSquared = squareValue(x);
in any of these 2 examples, will produce the same results...
Hence why every function in Javascript is a Function object.
The .constructor, .prototype, .toString on javascript Object/Function are all functions in their respective objects hence why you have the output as "function".
This is based according to the ECMA-262 3rd Edition -December 1999
Hope this helps.
reference Is every JavaScript Object a function?
javascript:alert([ window.navigator.userAgent, Object, Function ].join("\n\n") )
displays
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423
Ubuntu/10.04 (lucid) Firefox/3.6.3
function Object() {
[native code]
}
function Function() {
[native code]
}
also
javascript:alert([ new Object, new Function ].join("\n\n") )
displays
[object Object]
function anonymous() { }
and
javascript:alert([ new new Function ].join("\n\n") )
displays
[object Object]

Categories

Resources