对象在JavaScript中返回自身

时间:2014-02-28 14:12:47

标签: javascript google-chrome firefox

假设我有一个对象,它有一个返回对象本身的方法。

var mystate = {
    init: function() {
        return this;
    },
    run: function() {
        console.log("!");
    }
}

然后我运行这段代码:

var status = mystate.init();
mystate.run();
status.run();

在Firefox中,这会打印两个“!”控制台中的标志,但不知何故在Chrome中打印出第一个,但我收到错误,

  

未捕获的TypeError:对象[object Object]没有方法'run'

运行时status.run()

我在Chrome中运行status.run()时似乎状态未定义,但在Firefox中没有。

所以...为什么这样,我怎样才能使一个物体自行返回?

1 个答案:

答案 0 :(得分:5)

您无法在 Chrome 中设置status,因为您确实设置了window.status必须是 String

因此status成为 String "[object Object]"(即将 Object 转换为 String 的结果),并且 String 实例没有名为run的方法,因此您会收到错误。