Javascript Object.prototype.toString.call(currentFruit)==";[目标日期]”;
我是js的新手。。 我有一个if条件,因为我不理解if条件 你能告诉我如果情况真的。。。 Object.prototype.toString.call(currentFruit)=“[对象日期]” 你能解释一下吗。。。 在下面提供我的代码Javascript Object.prototype.toString.call(currentFruit)==";[目标日期]”;,javascript,jquery,html,css,javascript-events,Javascript,Jquery,Html,Css,Javascript Events,我是js的新手。。 我有一个if条件,因为我不理解if条件 你能告诉我如果情况真的。。。 Object.prototype.toString.call(currentFruit)=“[对象日期]” 你能解释一下吗。。。 在下面提供我的代码 setcurrentFruit: function (fruitName, currentFruit) { WorklistStorage.set(fruitName, currentFruit, false); }, getcurrentFruit:
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;
},
用于获取javascript对象的内部[[Class]]值。在这里,它测试currentFruit
是否为本机对象
它很容易被替换为(尽管有一些细微的区别)。让我们把它分解一下
- );本机JavaScript对象的引用
- );对对象的所有实例继承的属性的引用
- );所有对象的本机
方法toString
- );一种方法,用于使用选定的
Object.prototype.toString.call(currentFruit)
正在调用currentFruit
上所有对象的本机toString
。如果在currentFruit
上定义或继承了另一个toString
,则这可能不同于currentFruit.toString()
Object.prototype.toString
返回一个字符串,其形式为[Object X]
,其中X
是的类型,因此将[Object Date]
与===
进行比较是在询问“currentFruit
是日期吗?”
为什么执行此检查比执行其他检查更有用?因为typeof
通常只返回“object”
,这通常没有帮助
那怎么办?如果您正在检查的对象也继承了您正在测试的对象,那么这将是true
,因此,例如,x instanceof Object
通常是true
,这也并不总是有帮助
您可以认为类似的另一种方法是测试对象的构造函数<代码>x.constructor==日期。这有一组不同的问题,例如如果x
未定义或为空,则抛出错误,因此需要更多检查等。但是如果您使用非本机构造函数,toString
将简单地给出[对象对象]
,这将更有帮助
所有这些都说,考虑到你所处的环境,你需要考虑这个测试是否会是真的。目前没有日期的标准JSON表示形式。因为currentFruit是经过JSON解析的,所以您无法检查instanceof:似乎该日期在JSONJSON.parse(JSON.stringify(new Date())中不存在。instanceof Date===false
@HMR:我也曾预料到测试几乎没有意义,但是请注意,OP正在执行unescapeJSON
(可能有一些魔力)而不是JSON.parse
。