Reputation: 1751
I'm noob of javascript and I'm confused what's difference with following methods.
function foo(){};
var bar = new Object();
Object.prototype.toString.call(foo).slice(8, -1); // output "Function"
typeof foo; // output "function"
Object.prototype.toString.call(bar).slice(8, -1); // output "Object"
typeof bar; // output "object"
Upvotes: 5
Views: 4228
Reputation: 557
const str1 = "normal String"
const str2 = new String("using String constructor")
typeof str1 // 'string'
Object.protoType.toString.call(str1) // '[object String]'
typeof str2 // 'object'
Object.protoType.toString.call(str2) // '[object String]'
Object.protoType.toString.call(str2) can used to find string which are create using String constructor as our typeof doesn't work for the same
Upvotes: 0
Reputation: 20159
The most common application for the toString
'hack' is to figure out what type of object you're dealing with:
typeof(new Array()) === "object";
typeof(new Date()) === "object";
typeof(new RegExp()) === "object";
Object.prototype.toString.call(new Array()).slice(8, -1) === "Array";
Object.prototype.toString.call(new Date()).slice(8, -1) === "Date";
Object.prototype.toString.call(new RegExp()).slice(8, -1) === "RegExp";
For example, jQuery 1.11 uses this to check whether a given object is an array. jQuery 2 and higher uses the native Array.isArray
supported by modern browsers.
Besides, there are many cases where the two return different results, most commonly when using the object wrappers around primitive types:
typeof(new Number(5)) === "object";
Object.prototype.toString.call(new Number(5)).slice(8, -1) === "Number";
typeof(new String("hi")) === "object";
Object.prototype.toString.call(new String("hi")).slice(8, -1) === "String";
Upvotes: 6
Reputation: 301
toString() is a method, that returns a string that represents the current object (ex: Function). you can override it to return anything you want.
typeof is an operator. You use it to get the type of object (as a string). And you can not change (overloading) it like some other languages.
Upvotes: 0
Reputation: 55623
You can't override what gets returned from typeof
var MyObject = function() { };
MyObject.prototype.toString = function() { return undefined; }
var x = new MyObject();
console.log(typeof x);
console.log(x.toString());
If you're interested in JavaScript`s methods, check out MDN:
Upvotes: 3