2013-01-03 15 views
9

Sadece arguments değişkeninizin isimlendirilmesinin yanlış bir fikir olduğunu öğrendim. JavaScript tanımlayıcıları kullanmamak için

Output: []

Bu arguments her bir yeni çalışma bağlamında, arguments gölgelendiği "a local variable available within all functions" olduğu ortaya çıktı

var arguments = 5; 

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

Soruma göre: arguments gibi, reserved words gibi doğru olmayan başka hain isimler var, ama yine de sorunlara neden olacak mı?

+2

, (ayrı this' 'dan) işlevleri içinde başka otomatik sembolleri vardır. Her ne kadar bir dizi varsayılan global değişken olsa da, fonksiyon içinde aynı isimle bir değişken tanımlamak global değişkeni gölgeleyecektir. –

cevap

0

Orada fonksiyonları içeride başka otomatik sembollerdir (arayla this gelen, ancak yine bu isimde bir değişken oluşturmak olamaz), eğer anlatmak istediğin bu. Ama birkaç tane varsayılan global değişken var, bu yüzden fonksiyon içinde aynı isimle bir değişken tanımlamak global değişkeni gölgeleyecektir. Eğer demek buysa

+0

Bu gölge olabilir, ancak aynı zamanda gölge olmayabilir - bu tamamen tarayıcıya kadar, bu yüzden son cümle yanlıştır. Bu (aynı zamanda) neden bu küresel nesnelerin de sorunlu ve sadece düzenli, önceden tanımlanmış değişkenler değil. – eis

+0

@eis: Spesifikasyona göre, eğer belirli bir isimle bir yerel değişken varsa ve bu isme fonksiyonun içinde ulaşılırsa, o değişkenin değeri iade edilir (http://es5.github.com/#x10.2.2). .1). Sadece mevcut sözcük ortamında böyle bir sembol yoksa, "bir sonraki yüksek" olanı test edilir. Demek istediğim şey o. Ya da sen ne diyorsun? Bir fonksiyondaki her değişken bildirimin bir sembol yaratmadığı anlamına mı geliyor? Her iki durumda da somut bir örnek verebilir misiniz? –

+0

@FelixKing Tamam, sanırım şimdi farkın nerede olduğunu biliyorum. Örnek Aklımda vardı: 'var window = 5; (function() {window = 6; alert (window);})(); '- uyarı, pencere nesnesine yine de atadığımız değere değil, referans olur. Ancak işlev içinde 'var' ile açık bir şekilde bunu yalnızca işlev kapsamına atarız, bu durumda işe yarayacaktır. Ancak OP'nin örneği ile işe yaramazdı - basitçe, işlev ad alanı yerine genel ad alanında bildirildiğinden ve orada genel nesne ile çakışacak. – eis

8

Evet. Örneğin, window veya document gibi. Daha uzun bir liste here ("diğer javascript keyword") listesine bakın.

Bazılarının amaçlandığı gibi çalışmasına rağmen bunlardan herhangi birini kullanmanızı tavsiye etmem.

Düzenleme: javascript.about.com numaralı makalede bahsedildiği gibi, "Ayrılmış sözcük olmasalar bile, bu sözcüklerin değişkenler ve işlevler olarak kullanılmasından kaçınılmalıdır." Bunlar çoğunlukla predefined classes and objects ve global properties olarak sınıflandırılan aynı şeyleri listeliyorlar. Bir sorun

Örnek:

var window = 5; 

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

Yukarıdaki kod window pencere nesneye atıfta bulunmak için kelime olduğu gerçeği nedeniyle tahmin edilemeyen sonuçlar verir. Firefox, modifikasyonları önler, bu nedenle uyarı penceresi nesnesine başvurur, oysa IE8'de 5 değeri ile uyarı alırsınız.

+0

Bu sayfa, anahtar kelimelerin ne olduğu ve kategorilerin anlamsız olduğu anlaşılan yanlış anlaşılmalara dayanıyor gibi görünüyor.'window' ve' document' global değişkenler ve bu şekilde davranırlar, işte bu ... –

+0

@MathiasSchwarz: Daha iyi bir listeye sahipseniz, bunu bir yanıt olarak göndermekten memnuniyet duyarız. Sadece bazı iyi kelimelerin kategorizasyonuna katılmadığınız için mükemmel cevapları reddetmeyin. – Cerbrus

+0

@MathiasSchwarz Belki, ama sanırım zaten bu noktadan başka - OP, "argümanlar gibi, doğru yazılmış kelimeler değil, yine de sorunlara yol açacak diğer hain isimler" istiyordu, ve bu kesinlikle onlar. Anahtar kelimeler olduklarını iddia etmedim. – eis

0

Sen konsolunda bu yürüterek genel ad kullanılan tüm isimlerin listesini alabilirsiniz:

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

Sonuç: Yani

["$","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"]; 

, bu olamaz/olmamalı' Global kapsamda (en azından Google Chrome'da) kullanılmamalıdır. Bunları yerel bir kapsamda değişken olarak bildirirseniz, sorun yoktur. arguments örneğin, fonksiyon kapsamında yalnızca beri
Bu, tüm isimleri Ancak kullanılan içermeyecektir.

Not: Bu fonksiyon aynı zamanda, sizin kütüphanelerden tüm global değişkenleri çıkmıyor

+0

'arguments' global bir değişken değil. cevabım son satırına bakın: ekstra fonksiyon parametresi ... –

+0

@MathiasSchwarz sanki bu işlev başına tanımlanır. Bunu zaten söyledim. İndirgemeni kaldırırsan memnun olurum. – Cerbrus

+0

Sorun şu ki, küresel değişkenlerin sorulan soruyla ne ilgisi olduğunu göremiyorum. –

İlgili konular