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']