我是js新手。
我有一个if条件,因为我不了解if条件
你能告诉我如果条件允许怎么办...
Object.prototype.toString.call(currentFruit)===“[对象日期]”
你能解释一下吗?
在下面提供我的代码

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;
},

最佳答案

让我们分解一下;

  • Object ;本机JavaScript对象的引用。
  • Object.prototype ;对由Object的所有实例继承的属性的引用。
  • Object.prototype.toString ;所有对象的本机toString方法。
  • Function.prototype.call ;用选定的 this
  • 调用函数的方法

    因此,Object.prototype.toString.call(currentFruit)调用toString上所有对象的本机currentFruit。如果在currentFruit.toString()上定义了另一个toString或由currentFruit继承了另一个Object.prototype.toString,则此方法可能不同于[object X]
    X返回形式为this的字符串,其中[object Date]===的类型,因此将currentFruittypeof进行比较会问“typeof是日期吗?”

    为什么执行此检查比 "object" 有用?因为instanceof通常只会返回true,但这通常没有帮助。

    x instanceof Object 呢?如果您要检查的内容也继承自您要测试的内容,则它将为true,因此,例如x.constructor === Date通常是throw,这也不总是有用。

    您可能认为相似的另一种方法是测试Object的构造函数。 x。这有一系列不同的问题,例如如果toString未定义或为null,则[object Object]会出错,因此需要更多检查等。但是,如果您使用的是非本地构造函数,那么ojit_code会简单地给出ojit_code,这可能会更有帮助。

    综上所述,您需要考虑在您正在使用的环境下该测试是否正确。当前没有日期的标准JSON表示形式。

    10-04 22:11
    查看更多