Issue
I am new to js.
I have an if condition that I did not understand.
Can you tell me what this if condition does?
Object.prototype.toString.call(currentFruit) === "[object Date]"
Can you explain it? Providing my code below:
setcurrentFruit: function (fruitName, currentFruit) {
WorklistStorage.set(fruitName, currentFruit, false);
},
getcurrentFruit: function (fruitName) {
var currentFruit = unescapeJSON(WorklistStorage.get(fruitName, false));
if (currentFruit == "undefined" || typeof currentFruit == "undefined" || Object.prototype.toString.call(currentFruit) === "[object Date]") {
var date = new Date();
currentFruit = date.toString();
wholeQueue.setcurrentFruit(fruitName, currentFruit);
//console.log("poppppp");
}
currentFruit = new Date(currentFruit);
return currentFruit;
},
Solution
Let's break it down;
Object; the reference for native JavaScript Objects.Object.prototype; the reference to properties inherited by all instances of Object.Object.prototype.toString; the nativetoStringmethod of all Objects.Function.prototype.call; a method to invoke a function with a chosenthis
So Object.prototype.toString.call(currentFruit) is invoking the native toString of all Objects on currentFruit. This might be different to currentFruit.toString() if there is another toString defined on or inherited by currentFruit.
Object.prototype.toString returns a String of the form [object X] where X is the type of this, so comparing against [object Date] with === is asking "Is currentFruit a Date?"
Why is doing this check more useful than typeof? Because typeof will often just return "object", which is not often helpful.
What about instanceof? This will be true if the thing you're checking inherits from what you're testing against as well, so for example, x instanceof Object is usually true, which is not always helpful either.
An alternate method you could think of as similar would be to test the constructor of an Object. x.constructor === Date. This has a different set of problems, such as throwing errors if x is undefined or null so needs more checks etc. but it can be more helpful if you're working with non-native constructors, for which toString would simply give [object Object].
All this said, you need to consider whether this test will ever be true given the environment you're working with. Currently there is no standard JSON representation of a Date.
Answered By - Paul S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.