admin管理员组文章数量:1355602
If I type: window['alert']
in the console it will find the alert()
function.
However if I type: window['location.replace']
It will be undefined
. Why can't I access the location.replace
function?
If I type: window['alert']
in the console it will find the alert()
function.
However if I type: window['location.replace']
It will be undefined
. Why can't I access the location.replace
function?
5 Answers
Reset to default 7replace()
is a function found in the object window.location
, or window['location']
, so you will have to write:
window.location.replace
or
window['location']['replace']
What you want is window['location']['replace']
(or window['location'].replace
).
"location.replace" is not inside of "window". Rather, "replace" is inside of "location", which is inside of "window". Thus, it must be accessed in that order.
Because it's an object structure, not just the name with a dot. You can access it many different ways:
window.location.replace
window["location"].replace
window["location"]["replace"]
and so on…
If you want to continue the logic of window['alert']
use window['location']['replace']
.
When accessing window['location.replace']
the name of the property you are accessing is location.replace
, while what you want is the .replace
property of the object referenced to as window.location.
If you want to access objects by the so-called "object path" you need to construct a function that will split the object path "location.replace".split('.')
and then use recursion or a loop to reach to the property you're looking for.
Luckily there are packages for that, e.g. object- path that can do this job for you, but of course you need to consider whether you need a whole external library (albeit tiny) for your task.
See more about Bracket notation at MDN.
location function is under the window, but you can use directly this: location['replace']
本文标签: javascriptAccessing functions in the window objectStack Overflow
版权声明:本文标题:javascript - Accessing functions in the window object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743996399a2573067.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论