最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing functions in the window object - Stack Overflow

programmeradmin3浏览0评论

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?

Share Improve this question asked Aug 5, 2015 at 15:15 CameronCameron 28.9k102 gold badges289 silver badges490 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

replace() 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']

发布评论

评论列表(0)

  1. 暂无评论