7

昨晚,我真的很无聊,我想了一个小剧本的点子。基本上我在考虑 PHP 与 JavaScript 相比有多少内置函数,然后我意识到我真的不知道 JavaScript 实际有多少函数。我想编写一个脚本来查看窗口对象,包括对象内的每个对象等等。我编写了脚本并且它起作用了(在一个较小的对象上尝试过)。

但是,我的问题是 JavaScript 不会让我遍历整个 windows 对象。

我努力了:

for (var key in window) {
    console.log(key);
}

我也试过:

var a = Object.create(window);
for (var key in a) {
    console.log(key);
}

两段代码都给了我:

top
window
location
external
chrome
Intl
v8Intl
document
script1374438467163
$pick
$try
IFrame
Elements
OverText
IframeShim
Mask
Clientcide
dbug
value
debugCookie
StyleWriter
StickyWin
TabSwapper
Collapsible
Collapsable
Drag
Cookie
Accordion
Asset
Spinner
MultipleOpenAccordion
MooTools
typeOf
instanceOf
Type
Hash
Native
$A
$arguments
$chk
$clear
$defined
$each
$empty
$extend
$H
$merge
$lambda
$mixin
$random
$splat
$time
$type
$unlink
Browser
$constructor
Window
$family
Document
$exec
Slick
Element
uniqueNumber
$
getDocument
getWindow
Selectors
$$
addListener
removeListener
retrieve
store
eliminate
Class
Chain
Events
Options
Request
DOMEvent
Event
addEvent
removeEvent
addEvents
removeEvents
fireEvent
cloneEvents
Fx
Swiff
getSize
getScroll
getScrollSize
getPosition
getCoordinates
getHeight
getWidth
getScrollTop
getScrollLeft
getScrollHeight
getScrollWidth
getTop
getLeft
setCNETAssetBaseHref
Table
BehaviorAPI
Behavior
Color
$RGB
$HSB
$HEX
Keyboard
Locale
URI
CodeMirror
JSHINT
_
emmet
Sidebar
keyMods
Layout
MooShellActions
Base64
Dropdown
editorsModified
Track
update_resource_input
remove_resource
prepareToSubmit
submit_external_resource
change_default_input_value
validate
warn
disallowedPlatforms
default_code_mirror_options
MooShellEditor
MooShellSettings
disqus_developer
disqus_identifier
disqus_title
csspath
jspath
imgpath
mediapath
codemirrorpath
panel_html
panel_css
panel_js
makefavouritepath
example_server
username
static_hash
csrfToken
mooshell
preload_resources
DP
resources
default_text
add_external_resource_url
_gaq
TowTruckConfig_enableAnalytics
TowTruckConfig_cloneClicks
TowTruck
_gat
gaGlobal
style_html
css_beautify
js_beautify
Beautifier
language
Heyoffline
page_test
i
a
key
webkitNotifications
localStorage
sessionStorage
applicationCache
indexedDB
webkitIndexedDB
webkitStorageInfo
CSS
performance
console
devicePixelRatio
styleMedia
parent
opener
frames
self
defaultstatus
defaultStatus
status
name
length
closed
pageYOffset
pageXOffset
scrollY
scrollX
screenTop
screenLeft
screenY
screenX
innerWidth
innerHeight
outerWidth
outerHeight
offscreenBuffering
frameElement
crypto
clientInformation
navigator
toolbar
statusbar
scrollbars
personalbar
menubar
locationbar
history
screen
postMessage
close
blur
focus
ondeviceorientation
ontransitionend
onwebkittransitionend
onwebkitanimationstart
onwebkitanimationiteration
onwebkitanimationend
onsearch
onreset
onwaiting
onvolumechange
onunload
ontimeupdate
onsuspend
onsubmit
onstorage
onstalled
onselect
onseeking
onseeked
onscroll
onresize
onratechange
onprogress
onpopstate
onplaying
onplay
onpause
onpageshow
onpagehide
ononline
onoffline
onmousewheel
onmouseup
onmouseover
onmouseout
onmousemove
onmousedown
onmessage
onloadstart
onloadedmetadata
onloadeddata
onload
onkeyup
onkeypress
onkeydown
oninvalid
oninput
onhashchange
onfocus
onerror
onended
onemptied
ondurationchange
ondrop
ondragstart
ondragover
ondragleave
ondragenter
ondragend
ondrag
ondblclick
oncontextmenu
onclick
onchange
oncanplaythrough
oncanplay
onblur
onbeforeunload
onabort
getSelection
print
stop
open
showModalDialog
alert
confirm
prompt
find
scrollBy
scrollTo
scroll
moveBy
moveTo
resizeBy
resizeTo
matchMedia
setTimeout
clearTimeout
setInterval
clearInterval
requestAnimationFrame
cancelAnimationFrame
webkitRequestAnimationFrame
webkitCancelAnimationFrame
webkitCancelRequestAnimationFrame
atob
btoa
addEventListener
removeEventListener
captureEvents
releaseEvents
getComputedStyle
getMatchedCSSRules
webkitConvertPointFromPageToNode
webkitConvertPointFromNodeToPage
dispatchEvent
webkitRequestFileSystem
webkitResolveLocalFileSystemURL
openDatabase
TEMPORARY
PERSISTENT

但是,我知道 windows 对象内部还有很多属性。比如所有的SVG函数和HTML函数。为什么 JavaScript 会跳过对象中的许多属性?

4

1 回答 1

5

在现代浏览器中Object.getOwnPropertyNames()Object.getPrototypeOf()将帮助您获取原型链中所有对象的所有属性。

http://jsfiddle.net/FtVXN/

var obj = window;

do Object.getOwnPropertyNames(obj).forEach(function(name) {
       console.log(name);
   });
while(obj = Object.getPrototypeOf(obj));

如果您想查看原型对象的分离,则添加一条提供分隔线的线。

http://jsfiddle.net/FtVXN/1/

var obj = window;

do {
    Object.getOwnPropertyNames(obj).forEach(function(name) {
        console.log(name);
    });
    console.log("=============================");
} while(obj = Object.getPrototypeOf(obj));

我确实记得在 Firefox 中,一些全局变量在您访问它们之前不会出现。如果您发现是这种情况,您可能需要做一些试验。

于 2013-07-21T21:50:09.197 回答