2013-01-03 16 views
9

Właśnie odkryłem, że nazywanie zmiennej arguments jest złym pomysłem.Identyfikatory JavaScript nie używać

var arguments = 5; 

(function() { 
    console.log(arguments); 
})(); 

Output: []

Okazuje się, że arguments jest "a local variable available within all functions" więc w każdym nowym kontekście realizacji, arguments jest zasłonięta.

Moje pytanie brzmi: czy istnieją inne takie zdradzieckie nazwy, które, tak jak arguments, nie są prawdziwe reserved words, ale czy będą nadal powodować problemy?

+2

Wewnątrz funkcji nie ma innych symboli automatycznych (oprócz "tego"), jeśli o to ci chodzi. Chociaż istnieje kilka domyślnych zmiennych globalnych, więc zdefiniowanie zmiennej o tej samej nazwie wewnątrz funkcji spowoduje przesłonięcie zmiennej globalnej. –

Odpowiedz

0

Nie ma żadnych innych automatycznych symbole wewnątrz funkcji (oprócz this, ale nie można utworzyć zmienną o tej nazwie i tak), jeśli to masz na myśli. Ale istnieje kilka domyślnych zmiennych globalnych, więc zdefiniowanie zmiennej o tej samej nazwie wewnątrz funkcji spowoduje przesłonięcie zmiennej globalnej.

+0

Może cienia, ale może również nie cienia - to całkowicie do przeglądarki, więc ostatnie zdanie jest błędne. To także (dlaczego) te globalne obiekty również są problematyczne i nie są zwykłymi, predefiniowanymi zmiennymi. – eis

+0

@eis: Według specyfikacji, jeśli istnieje lokalna zmienna o określonej nazwie i ta nazwa jest dostępna wewnątrz funkcji, zwracana jest wartość tej zmiennej (http://es5.github.com/#x10.2.2 .1). Tylko jeśli nie ma takiego symbolu w aktualnym środowisku leksykalnym, testowany jest "następny wyższy". O to mi chodziło. Albo do czego się odnosisz? Czy masz na myśli to, że nie każda deklaracja zmiennej w funkcji tworzy symbol? Tak czy inaczej, czy mógłbyś podać konkretny przykład? –

+0

@FelixKing Ok, myślę, że wiem, gdzie jest różnica. Przykład miałem na myśli: 'var window = 5; (function() {window = 6; alert (window);})(); '- alert nadal będzie odwoływał się do obiektu window, a nie do wartości, którą do niego przypisaliśmy. Ale z 'var' w funkcji jawnie przyporządkowujemy ją tylko do zakresu funkcji, w którym to przypadku by działało. Ale nie zadziałałoby to na przykładzie OP - po prostu dlatego, że zmienna jest zadeklarowana w globalnej przestrzeni nazw zamiast przestrzeni nazw funkcji, i tam będzie kolidować z obiektem globalnym. – eis

8

Tak. Na przykład: window lub document. Zobacz dłuższą listę here ("inne słowa kluczowe javascript").

Nie zaleca się używania żadnego z nich, nawet jeśli niektóre będą działać zgodnie z przeznaczeniem.

Edytuj: Jak wspomniano w javascript.about.com, "Mimo że nie są słowami zastrzeżonymi, należy unikać używania tych słów jako zmiennych i funkcji.". Zawierają one głównie te same rzeczy, które zostały sklasyfikowane jako predefined classes and objects i .

Przykład problemu:

var window = 5; 

(function() { 
    alert(window); 
})(); 

powyższy kod ma nieprzewidywalne wyniki ze względu na fakt, że window to słowo odnosi się do obiektu window. Firefox zapobiega modyfikacjom, więc alarm będzie nadal odnosił się do obiektu okna, podczas gdy w IE8 dostaniesz alert o wartości 5.

+0

Ta strona wydaje się być zbudowana na niezrozumieniu słów kluczowych, a kategorie wydają się mało sensowne.'window' i' document' są zmiennymi globalnymi i zachowują się jako takie, to jest to ... –

+0

@MathiasSchwarz: Jeśli masz lepszą listę, możesz ją opublikować jako odpowiedź. Nie notuj idealnie dobrych odpowiedzi tylko dlatego, że nie zgadzasz się z kategoryzacją niektórych słów. – Cerbrus

+0

@MathiasSchwarz Może, ale myślę, że i tak jest poza tym punktem - OP prosił o "inne takie zdradzieckie imiona, które, jak argumenty, nie są prawdziwymi słowami zastrzeżonymi, ale będą powodować nadal problemy", i to z pewnością są. Nie twierdziłem, że są to słowa kluczowe. – eis

0

można uzyskać listę wszystkich nazw stosowanych w globalnej przestrzeni nazw, wykonując to w konsoli:

var t = []; 
for(v in this){t.push(v)} 
console.log(t.sort()); 

Wynik:

["$","ArrayBuffer","Attr","Audio","AudioProcessingEvent","BeforeLoadEvent","Blob","CDATASection","CSSCharsetRule","CSSFontFaceRule","CSSImportRule","CSSMediaRule","CSSPageRule","CSSPrimitiveValue","CSSRule","CSSRuleList","CSSStyleDeclaration","CSSStyleRule","CSSStyleSheet","CSSValue","CSSValueList","CTIsPlayback","CanvasGradient","CanvasPattern","CanvasRenderingContext2D","CharacterData","ClientRect","ClientRectList","Clipboard","CloseEvent","Comment","CompositionEvent","Counter","CustomEvent","DOMException","DOMImplementation","DOMParser","DOMSettableTokenList","DOMStringList","DOMStringMap","DOMTokenList","DataView","DeviceOrientationEvent","Document","DocumentFragment","DocumentType","Element","Entity","EntityReference","ErrorEvent","Event","EventEmitter","EventException","EventSource","File","FileError","FileList","FileReader","Float32Array","Float64Array","FormData","Generator","HTMLAllCollection","HTMLAnchorElement","HTMLAppletElement","HTMLAreaElement","HTMLAudioElement","HTMLBRElement","HTMLBaseElement","HTMLBaseFontElement","HTMLBodyElement","HTMLButtonElement","HTMLCanvasElement","HTMLCollection","HTMLDListElement","HTMLDataListElement","HTMLDirectoryElement","HTMLDivElement","HTMLDocument","HTMLElement","HTMLEmbedElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormElement","HTMLFrameElement","HTMLFrameSetElement","HTMLHRElement","HTMLHeadElement","HTMLHeadingElement","HTMLHtmlElement","HTMLIFrameElement","HTMLImageElement","HTMLInputElement","HTMLKeygenElement","HTMLLIElement","HTMLLabelElement","HTMLLegendElement","HTMLLinkElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMenuElement","HTMLMetaElement","HTMLMeterElement","HTMLModElement","HTMLOListElement","HTMLObjectElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOutputElement","HTMLParagraphElement","HTMLParamElement","HTMLPreElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSourceElement","HTMLSpanElement","HTMLStyleElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTextAreaElement","HTMLTitleElement","HTMLTrackElement","HTMLUListElement","HTMLUnknownElement","HTMLVideoElement","HashChangeEvent","IceCandidate","Image","ImageData","Int16Array","Int32Array","Int8Array","KeyboardEvent","Markdown","MediaController","MediaError","MediaList","MediaStreamEvent","MessageChannel","MessageEvent","MessagePort","MimeType","MimeTypeArray","MouseEvent","MutationEvent","NamedNodeMap","Node","NodeFilter","NodeList","Notation","Notification","OfflineAudioCompletionEvent","Option","OverflowEvent","PERSISTENT","PR","PR_SHOULD_USE_CONTINUATION","PageTransitionEvent","Plugin","PluginArray","PopStateEvent","ProcessingInstruction","ProgressEvent","RGBColor","RTCIceCandidate","RTCSessionDescription","Range","RangeException","Rect","SQLException","SVGAElement","SVGAltGlyphDefElement","SVGAltGlyphElement","SVGAltGlyphItemElement","SVGAngle","SVGAnimateColorElement","SVGAnimateElement","SVGAnimateMotionElement","SVGAnimateTransformElement","SVGAnimatedAngle","SVGAnimatedBoolean","SVGAnimatedEnumeration","SVGAnimatedInteger","SVGAnimatedLength","SVGAnimatedLengthList","SVGAnimatedNumber","SVGAnimatedNumberList","SVGAnimatedPreserveAspectRatio","SVGAnimatedRect","SVGAnimatedString","SVGAnimatedTransformList","SVGCircleElement","SVGClipPathElement","SVGColor","SVGComponentTransferFunctionElement","SVGCursorElement","SVGDefsElement","SVGDescElement","SVGDocument","SVGElement","SVGElementInstance","SVGElementInstanceList","SVGEllipseElement","SVGException","SVGFEBlendElement","SVGFEColorMatrixElement","SVGFEComponentTransferElement","SVGFECompositeElement","SVGFEConvolveMatrixElement","SVGFEDiffuseLightingElement","SVGFEDisplacementMapElement","SVGFEDistantLightElement","SVGFEDropShadowElement","SVGFEFloodElement","SVGFEFuncAElement","SVGFEFuncBElement","SVGFEFuncGElement","SVGFEFuncRElement","SVGFEGaussianBlurElement","SVGFEImageElement","SVGFEMergeElement","SVGFEMergeNodeElement","SVGFEMorphologyElement","SVGFEOffsetElement","SVGFEPointLightElement","SVGFESpecularLightingElement","SVGFESpotLightElement","SVGFETileElement","SVGFETurbulenceElement","SVGFilterElement","SVGFontElement","SVGFontFaceElement","SVGFontFaceFormatElement","SVGFontFaceNameElement","SVGFontFaceSrcElement","SVGFontFaceUriElement","SVGForeignObjectElement","SVGGElement","SVGGlyphElement","SVGGlyphRefElement","SVGGradientElement","SVGHKernElement","SVGImageElement","SVGLength","SVGLengthList","SVGLineElement","SVGLinearGradientElement","SVGMPathElement","SVGMarkerElement","SVGMaskElement","SVGMatrix","SVGMetadataElement","SVGMissingGlyphElement","SVGNumber","SVGNumberList","SVGPaint","SVGPathElement","SVGPathSeg","SVGPathSegArcAbs","SVGPathSegArcRel","SVGPathSegClosePath","SVGPathSegCurvetoCubicAbs","SVGPathSegCurvetoCubicRel","SVGPathSegCurvetoCubicSmoothAbs","SVGPathSegCurvetoCubicSmoothRel","SVGPathSegCurvetoQuadraticAbs","SVGPathSegCurvetoQuadraticRel","SVGPathSegCurvetoQuadraticSmoothAbs","SVGPathSegCurvetoQuadraticSmoothRel","SVGPathSegLinetoAbs","SVGPathSegLinetoHorizontalAbs","SVGPathSegLinetoHorizontalRel","SVGPathSegLinetoRel","SVGPathSegLinetoVerticalAbs","SVGPathSegLinetoVerticalRel","SVGPathSegList","SVGPathSegMovetoAbs","SVGPathSegMovetoRel","SVGPatternElement","SVGPoint","SVGPointList","SVGPolygonElement","SVGPolylineElement","SVGPreserveAspectRatio","SVGRadialGradientElement","SVGRect","SVGRectElement","SVGRenderingIntent","SVGSVGElement","SVGScriptElement","SVGSetElement","SVGStopElement","SVGStringList","SVGStyleElement","SVGSwitchElement","SVGSymbolElement","SVGTRefElement","SVGTSpanElement","SVGTextContentElement","SVGTextElement","SVGTextPathElement","SVGTextPositioningElement","SVGTitleElement","SVGTransform","SVGTransformList","SVGUnitTypes","SVGUseElement","SVGVKernElement","SVGViewElement","SVGViewSpec","SVGZoomAndPan","SVGZoomEvent","Selection","SessionDescription","SharedWorker","SpeechInputEvent","StackExchange","Storage","StorageEvent","StyleSheet","StyleSheetList","TEMPORARY","Text","TextEvent","TextMetrics","TextTrack","TextTrackCue","TextTrackCueList","TextTrackList","TimeRanges","TouchEvent","TrackEvent","UIEvent","URL","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray","WebGLActiveInfo","WebGLBuffer","WebGLContextEvent","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLRenderingContext","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebKitAnimationEvent","WebKitBlobBuilder","WebKitCSSFilterValue","WebKitCSSKeyframeRule","WebKitCSSKeyframesRule","WebKitCSSMatrix","WebKitCSSRegionRule","WebKitCSSTransformValue","WebKitIntent","WebKitMediaSource","WebKitMutationObserver","WebKitPoint","WebKitSourceBuffer","WebKitSourceBufferList","WebKitTransitionEvent","WebSocket","WheelEvent","Window","WinterBash","Worker","XMLDocument","XMLHttpRequest","XMLHttpRequestException","XMLHttpRequestProgressEvent","XMLHttpRequestUpload","XMLSerializer","XPathEvaluator","XPathException","XPathResult","XSLTProcessor","__qc","_gaq","_gat","_qevents","addEventListener","alert","apiCallbacks","applicationCache","atob","blur","btoa","captureEvents","careers_adselector","careers_adurl","careers_companycssurl","careers_cssurl","careers_leaderboardcssurl","chrome","clearInterval","clearTimeout","clientInformation","close","closed","confirm","console","crypto","defaultStatus","defaultstatus","devicePixelRatio","dispatchEvent","document","event","external","find","focus","frameElement","frames","gaGlobal","gauth","genuwine","getComputedStyle","getMatchedCSSRules","getSelection","history","i","initFadingHelpText","initTagRenderer","innerHeight","innerWidth","jQuery","jQuery171005593172716908157_1357215797040","jQuery171005593172716908157_1357215797041","length","localStorage","location","locationbar","matchMedia","menubar","moveBy","moveScroller","moveTo","name","navigator","offscreenBuffering","onabort","onbeforeunload","onblur","oncanplay","oncanplaythrough","onchange","onclick","oncontextmenu","ondblclick","ondeviceorientation","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onhashchange","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmessage","onmousedown","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onoffline","ononline","onpagehide","onpageshow","onpause","onplay","onplaying","onpopstate","onprogress","onratechange","onreset","onresize","onscroll","onsearch","onseeked","onseeking","onselect","onstalled","onstorage","onsubmit","onsuspend","ontimeupdate","onunload","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","open","openDatabase","opener","outerHeight","outerWidth","pageXOffset","pageYOffset","parent","performance","personalbar","postMessage","prepareEditor","prettyPrint","prettyPrintOne","print","profileLink","prompt","quantserve","releaseEvents","removeEventListener","resizeBy","resizeTo","sanitizeAndSplitTags","screen","screenLeft","screenTop","screenX","screenY","scriptSrc","scroll","scrollBy","scrollTo","scrollX","scrollY","scrollbars","self","sessionStorage","setInterval","setTimeout","showFadingHelpText","showModalDialog","status","statusbar","stop","styleCode","styleMedia","t","tagRenderer","tagRendererRaw","toolbar","top","uh","v","v8Intl","votesCast","webkitAudioContext","webkitAudioPannerNode","webkitCancelAnimationFrame","webkitCancelRequestAnimationFrame","webkitConvertPointFromNodeToPage","webkitConvertPointFromPageToNode","webkitIDBCursor","webkitIDBDatabase","webkitIDBDatabaseException","webkitIDBFactory","webkitIDBIndex","webkitIDBKeyRange","webkitIDBObjectStore","webkitIDBRequest","webkitIDBTransaction","webkitIndexedDB","webkitIntent","webkitMediaStream","webkitNotifications","webkitPostMessage","webkitRTCPeerConnection","webkitRequestAnimationFrame","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","webkitStorageInfo","webkitURL","window"]; 

Tak, to nie mogę/powinnam” być używane (przynajmniej w Google Chrome) w zakresie globalnym. Jeśli zadeklarujesz je jako zmienne w zakresie lokalnym, wszystko będzie dobrze.
Nie będzie to zawierało nazw all, ponieważ arguments jest dostępne tylko w zakresie funkcji, na przykład.

Uwaga: ta funkcja nie zwróci wszystkie zmienne globalne z bibliotek, również

+0

'arguments' nie jest zmienną globalną. Jest zdefiniowany dla funkcji tak, jakby był dodatkowym parametrem funkcji ... –

+0

@MathiasSchwarz: Spójrz na ostatni wiersz mojej odpowiedzi. Już to powiedziałem. Byłbym wdzięczny, gdybyś usunął swoje poparcie. – Cerbrus

+0

Problem polega na tym, że naprawdę nie widzę zmiennych globalnych związanych z zadawanym pytaniem. –

Powiązane problemy