Javascript 历史推送状态不在standalone location.hash或location.href中,但在location对象本身中

Javascript 历史推送状态不在standalone location.hash或location.href中,但在location对象本身中,javascript,html,pushstate,html5-history,Javascript,Html,Pushstate,Html5 History,有人能解释这种行为吗?我使用history.pushState(null,null,#test')推送历史状态。然后,当尝试使用console.log(window.location.hash)在侦听器函数中获取状态URL时(没有找到更好的方法来侦听pushState更改),它返回空字符串\testhashconsole.log(window.location.href)返回整个URL,不带哈希#test,但console.log(window.location)返回location对象,其中哈

有人能解释这种行为吗?我使用
history.pushState(null,null,#test')推送历史状态。然后,当尝试使用
console.log(window.location.hash)
在侦听器函数中获取状态URL时(没有找到更好的方法来侦听pushState更改),它返回空字符串
\test
hash
console.log(window.location.href)
返回整个URL,不带哈希
#test
,但
console.log(window.location)
返回
location
对象,其中哈希同时位于
href
哈希
属性中。为什么会这样?我怎样才能获得推送状态的URL

        (function(history){
            var pushState = history.pushState;
            history.pushState = function(state) {
                if (typeof history.onpushstate == "function") {
                    history.onpushstate({state: state});
                }
                console.log(window.location.hash);
                console.log(window.location.href);
                console.log(window.location);
                return pushState.apply(history, arguments);
            }
        })(window.history);

        history.pushState(null, null, '#test');

这是因为您在实际设置新状态之前记录了变量。之所以可以在对象中看到更新的属性,是因为它记录了对对象的引用,而不是记录对象时的副本。直到这一行,您的monkey补丁才会调用原始的
pushState
函数

return pushState.apply(history, arguments);
为了解决这个问题,您可以在登录之前简单地调用函数,然后返回响应

(function(history){
    var pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        var r = pushState.apply(history, arguments);
        console.log(window.location.hash);
        console.log(window.location.href);
        console.log(window.location);
        return r;
    }
})(window.history);

history.pushState(null, null, '#test');

哦,我没注意到。但是为什么它在
window.location
而不是
window.location.hash
中应用之前对我来说仍然有点神秘…@simPod当你
console.log
一个对象时,它是对该对象的实时引用。如果属性在日志记录后更改,则在检查对象时,您将看到更新的属性。