javascript 重学前端系列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 重学前端系列相关的知识,希望对你有一定的参考价值。
// 展示出页面中所有html节点
// getDomObj.js
var domId = 0 // 节点树
var domObj = [] // 平级dom节点
var domTree = [ // 树形dom结构
{
id: "HTML_0",
tagName: 'HTML',
parentFlag: '',
children: []
}
]
var temptree = null
var getElemts = function(parent, parentFlag) {
var children = parent.children
domId += 1
for(var i = 0; i < children.length; i++) {
let tag = children[i]
var dom = {
id: tag.tagName+'_'+domId,
tagName: tag.tagName,
parentFlag: parentFlag,
}
domTree.push(dom)
if (tag.children) {
getElemts(tag, tag.tagName+'_'+domId)
}
}
}
var diff = function(data, parentFlag) {
var result = [], temp;
for (var i in data) {
if (data[i].parentFlag == parentFlag) {
result.push(data[i]);
temp = diff(data, data[i].id);
if (temp.length > 0) {
data[i].children = temp;
}
}
}
return result;
}
Array.prototype.ToTree = function (parentFlag) {
var result = [], temp;
for (var i in this) {
if (this[i].parentFlag == parentFlag) {
result.push(this[i]);
temp = diff(this, this[i].id);
if (temp.length > 0) {
this[i].children = temp;
}
}
}
return result
}
var showDom = function () {
var doc = document.getElementsByTagName('html')
getElemts(doc[0], 'HTML_0')
domTree = domTree.ToTree('')
}
showDom()
console.log(domTree)
// 浏览器中过滤出所有api
function filterOut(names, props) {
let set = new Set();
props.forEach(o => set.add(o));
return names.filter(e => !set.has(e));
}
{
// 所有api
var names = Object.getOwnPropertyNames(window)
//JavaScript 中规定的 API
var objects = ["BigInt", "BigInt64Array", "BigUint64Array", "Infinity", "NaN", "undefined", "eval", "isFinite", "isNaN", "parseFloat", "parseInt", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "Array", "Date", "RegExp", "Promise", "Proxy", "Map", "WeakMap", "Set", "WeakSet", "Function", "Boolean", "String", "Number", "Symbol", "Object", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint16Array", "Uint32Array", "Uint8ClampedArray", "Atomics", "JSON", "Math", "Reflect", "escape", "unescape"];
names = filterOut(names, objects)
// 所有dom中的元素构造器
names = names.filter( e => {
try {
return !(window[e].prototype instanceof Node)
} catch(err) {
return true;
}
}).filter( e => e != "Node")
// Window 对象上的属性
objects = ["window", "self", "document", "name", "location", "history", "customElements", "locationbar", "menubar", " personalbar", "scrollbars", "statusbar", "toolbar", "status", "close", "closed", "stop", "focus", " blur", "frames", "length", "top", "opener", "parent", "frameElement", "open", "navigator", "applicationCache", "alert", "confirm", "prompt", "print", "postMessage"]
names = filterOut(names, objects)
// 过滤所有事件
names = names.filter( e => !e.match(/^on/))
// webkit 前缀的私有属性
names = names.filter( e => !e.match(/^webkit/i))
// HTML 标准中 所有的接口
objects = ["NodeList", "NodeIterator", "NodeFilter", "NamedNodeMap", "ApplicationCache", "AudioTrack", "AudioTrackList", "BarProp", "BeforeUnloadEvent", "BroadcastChannel", "CanvasGradient", "CanvasPattern", "CanvasRenderingContext2D", "CloseEvent", "CustomElementRegistry", "DOMStringList", "DOMStringMap", "DataTransfer", "DataTransferItem", "DataTransferItemList", "DedicatedWorkerGlobalScope", "Document", "DragEvent", "ErrorEvent", "EventSource", "External", "FormDataEvent", "HTMLAllCollection", "HashChangeEvent", "History", "ImageBitmap", "ImageBitmapRenderingContext", "ImageData", "Location", "MediaError", "MessageChannel", "MessageEvent", "MessagePort", "MimeType", "MimeTypeArray", "Navigator", "OffscreenCanvas", "OffscreenCanvasRenderingContext2D", "PageTransitionEvent", "Path2D", "Plugin", "PluginArray", "PopStateEvent", "PromiseRejectionEvent", "RadioNodeList", "SharedWorker", "SharedWorkerGlobalScope", "Storage", "StorageEvent", "TextMetrics", "TextTrack", "TextTrackCue", "TextTrackCueList", "TextTrackList", "TimeRanges", "TrackEvent", "ValidityState", "VideoTrack", "VideoTrackList", "WebSocket", "Window", "Worker", "WorkerGlobalScope", "WorkerLocation", "WorkerNavigator", "DOMTokenList", "DOMRectReadOnly", "DOMRectList", "DOMRect", "DOMQuad", "DOMPointReadOnly", "DOMPoint", "DOMParser", "DOMMatrixReadOnly", "DOMMatrix", "DOMImplementation", "DOMException", "DOMError"];
names = filterOut(names, objects)
// ECMAScript 2018 Internationalization API
names = names.filter(e => e != "Intl")
// Streams 标准
objects = ["ReadableStream", "ReadableStreamDefaultReader", "ReadableStreamBYOBReader", "ReadableStreamDefaultController", "ReadableByteStreamController", "ReadableStreamBYOBRequest", "WritableStream", "WritableStreamDefaultWriter", "WritableStreamDefaultController", "TransformStream", "TransformStreamDefaultController", "ByteLengthQueuingStrategy", "CountQueuingStrategy"]
names = filterOut(names, objects);
// WEBGL
names = names.filter( e => !e.match(/^webgl/i));
// Web Audio API
objects = ["OfflineAudioContext", "OfflineAudioCompletionEvent", "AudioScheduledSourceNode", "AudioParamMap", "AudioContext", "AudioNode", "AnalyserNode", "AudioBuffer", "AudioBufferSourceNode", "AudioDestinationNode", "AudioParam", "AudioListener", "AudioWorklet", "AudioWorkletGlobalScope", "AudioWorkletNode", "AudioWorkletProcessor", "BiquadFilterNode", "ChannelMergerNode", "ChannelSplitterNode", "ConstantSourceNode", "ConvolverNode", "DelayNode", "DynamicsCompressorNode", "GainNode", "IIRFilterNode", "MediaElementAudioSourceNode", "MediaStreamAudioSourceNode", "MediaStreamTrackAudioSourceNode", "MediaStreamAudioDestinationNode", 'MediaStreamTrackEvent', 'MediaStreamTrack', 'MediaStreamEvent', 'MediaStream', "PannerNode", "PeriodicWave", "OscillatorNode", "StereoPannerNode", "WaveShaperNode", "ScriptProcessorNode", "AudioProcessingEvent"]
names = filterOut(names, objects);
// Encoding 标准
objects = ["TextDecoder", "TextEncoder", "TextDecoderStream", "TextEncoderStream"]
names = filterOut(names, objects);
// Web Background Synchronization
// https://wicg.github.io/BackgroundSync/spec/#sync-manager-interface
names = filterOut(names, ["SyncManager"]);
// Web Cryptography API
// https://www.w3.org/TR/WebCryptoAPI/
names = filterOut(names, ["CryptoKey", "SubtleCrypto", "Crypto", "crypto"]);
// Media Source Extensions
// https://www.w3.org/TR/media-source/
names = filterOut(names, ["MediaSource", "SourceBuffer", "SourceBufferList", "MediaSettingsRange", "MediaRecorder", "MediaEncryptedEvent", "MediaDevices", "MediaDeviceInfo", "MediaCapabilities"]);
// The Screen Orientation API
// https://www.w3.org/TR/screen-orientation/
names = filterOut(names, ["ScreenOrientation"]);
// SVG
objects = ["SVGUnitTypes", "SVGTransformList", "SVGTransform", "SVGStringList", "SVGRect", "SVGPreserveAspectRatio", "SVGPointList", "SVGPoint", "SVGNumberList", "SVGNumber", "SVGMatrix", "SVGLengthList", "SVGLength", "SVGAnimatedTransformList", "SVGAnimatedString", "SVGAnimatedRect", "SVGAnimatedPreserveAspectRatio", "SVGAnimatedNumberList", "SVGAnimatedNumber", "SVGAnimatedLengthList", "SVGAnimatedLength", "SVGAnimatedInteger", "SVGAnimatedEnumeration", "SVGAnimatedBoolean", "SVGAnimatedAngle", "SVGAngle"]
names = filterOut(names, objects);
// WebRTC,名称源自网页即时通信
objects = ["RTCTrackEvent", "RTCStatsReport", "RTCSessionDescription", "RTCRtpTransceiver", "RTCRtpSender", "RTCRtpReceiver", "RTCPeerConnectionIceEvent", "RTCPeerConnection", "RTCIceCandidate", "RTCDataChannelEvent", "RTCDataChannel", "RTCDTMFToneChangeEvent", "RTCDTMFSender", "RTCCertificate"]
names = filterOut(names, objects);
// performance 页访问某些函数来测量网页和Web应用程序的性能
objects = ["PerformanceTiming", "PerformanceServerTiming", "PerformanceResourceTiming", "PerformancePaintTiming", "PerformanceObserverEntryList", "PerformanceObserver", "PerformanceNavigationTiming", "PerformanceNavigation", "PerformanceMeasure", "PerformanceMark", "PerformanceLongTaskTiming", "PerformanceEntry", "Performance",]
names = filterOut(names, objects);
// midi “Js生成数字音乐” 用Javascript抽象Midi文件结构
objects = ["MIDIPort", "MIDIOutputMap", "MIDIOutput", "MIDIMessageEvent", "MIDIInputMap", "MIDIInput", "MIDIConnectionEvent", "MIDIAccess",]
names = filterOut(names, objects);
// index db 浏览器数据库
objects = [ "IDBVersionChangeEvent", "IDBTransaction", "IDBRequest", "IDBOpenDBRequest", "IDBObjectStore", "IDBKeyRange", "IDBIndex", "IDBFactory", "IDBDatabase", "IDBCursorWithValue", "IDBCursor"]
names = filterOut(names, objects);
// xpath
objects = ["XPathResult", "XPathExpression", "XPathEvaluator"]
names = filterOut(names, objects);
// xml http request
objects = ["XMLSerializer", "XMLHttpRequestUpload", "XMLHttpRequestEventTarget", "XMLHttpRequest"]
names = filterOut(names, objects);
// CSS
objects = ["StyleSheetList","StyleSheet","StylePropertyMapReadOnly","StylePropertyMap", "CSSVariableReferenceValue", "CSSUnparsedValue", "CSSUnitValue", "CSSTranslate", "CSSTransformValue", "CSSTransformComponent", "CSSSupportsRule", "CSSStyleValue", "CSSStyleSheet", "CSSStyleRule", "CSSStyleDeclaration", "CSSSkewY", "CSSSkewX", "CSSSkew", "CSSScale", "CSSRuleList", "CSSRule", "CSSRotate", "CSSPositionValue", "CSSPerspective", "CSSPageRule", "CSSNumericValue", "CSSNumericArray", "CSSNamespaceRule", "CSSMediaRule", "CSSMatrixComponent", "CSSMathValue", "CSSMathSum", "CSSMathProduct", "CSSMathNegate", "CSSMathMin", "CSSMathMax", "CSSMathInvert", "CSSKeywordValue", "CSSKeyframesRule", "CSSKeyframeRule", "CSSImportRule", "CSSImageValue", "CSSGroupingRule", "CSSFontFaceRule", "CSS", "CSSConditionRule"]
names = filterOut(names, objects);
// payment
objects = ["PaymentInstruments", "PaymentManager", "PaymentRequestUpdateEvent", "PaymentAddress", "PaymentRequest", "PaymentResponse"]
names = filterOut(names, objects);
// Presentation API的目标就是让投影仪或TV这样的第二显示设备能够被Web使用,
// 包括所有通过有线(HDMI,DVI等)连接以及通过无线(MiraCast, Chromecast, DLNA, AirPlay等)的设备。
// 这个API所做的就是在请求页面与第二显示设备上的演示页面之间实现消息互通。
objects = ["Presentation", "PresentationAvailability", "PresentationConnection", "PresentationConnectionAvailableEvent", "PresentationConnectionCloseEvent", "PresentationConnectionList", "PresentationReceiver", "PresentationRequest"]
names = filterOut(names, objects);
// usb
objects = ["USB", "USBAlternateInterface", "USBConfiguration", "USBConnectionEvent", "USBDevice", "USBEndpoint", "USBInterface", "USBInTransferResult", "USBIsochronousInTransferPacket", "USBIsochronousInTransferResult", "USBIsochronousOutTransferPacket", "USBIsochronousOutTransferResult", "USBOutTransferResult"]
names = filterOut(names, objects);
// 蓝牙
objects = ["BluetoothUUID","Bluetooth","BluetoothCharacteristicProperties","BluetoothDevice","BluetoothRemoteGATTCharacteristic","BluetoothRemoteGATTDescriptor","BluetoothRemoteGATTServer","BluetoothRemoteGATTService"]
names = filterOut(names, objects);
// 游戏手柄 Gamepad
names = names.filter( e => !e.match(/^gamepad/i));
// 网页语音 API 的SpeechSynthesis 接口是语音服务的控制接口;
// 它可以用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令。
names = names.filter( e => !e.match(/^speechSynthesis/i));
}
// 基于原型链创建对象的两种方法
function c1(){
this.p1 = 1;
this.p2 = function(){
console.log(this.p1);
}
}
var o1 = new c1;
o1.p2();
function c2(){
}
c2.prototype.p1 = 1;
c2.prototype.p2 = function(){
console.log(this.p1);
}
var o2 = new c2;
o2.p2();
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
var r = new Rectangle(2, 2)
r.area()
r.calcArea()
// 列出所有固有对象
var set = new Set();
var objects = [
eval,
isFinite,
isNaN,
parseFloat,
parseInt,
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
Array,
Date,
RegExp,
Promise,
Proxy,
Map,
WeakMap,
Set,
WeakSet,
Function,
Boolean,
String,
Number,
Symbol,
Object,
Error,
EvalError,
RangeError,
ReferenceError,
SyntaxError,
TypeError,
URIError,
ArrayBuffer,
SharedArrayBuffer,
DataView,
Float32Array,
Float64Array,
Int8Array,
Int16Array,
Int32Array,
Uint8Array,
Uint16Array,
Uint32Array,
Uint8ClampedArray,
Atomics,
JSON,
Math,
Reflect
];
objects.forEach(o => set.add(o));
for(var i = 0; i < objects.length; i++) {
var o = objects[i]
for(var p of Object.getOwnPropertyNames(o)) {
var d = Object.getOwnPropertyDescriptor(o, p)
if( (d.value !== null && typeof d.value === "object") || (typeof d.value === "function"))
if(!set.has(d.value))
set.add(d.value), objects.push(d.value);
if( d.get )
if(!set.has(d.get))
set.add(d.get), objects.push(d.get);
if( d.set )
if(!set.has(d.set))
set.add(d.set), objects.push(d.set);
}
}
// 在宏观任务中,JavaScript 的 Promise 还会产生异步代码,
// JavaScript 必须保证这些异步代码在一个宏观任务中完成,
// so,每个宏观任务中又包含了一个微观任务队列
var r = new Promise(function(resolve, reject){
console.log("a");
resolve()
});
setTimeout(()=>console.log("d"), 0)
r.then(() => console.log("c"));
console.log("b")
// 执行结果
// a b c d
// 实现一个红绿灯,把一个圆形 div 按照绿色3 秒,黄色 1 秒,红色 2 秒循环改变背景色
// 初始化创建元素
var div = document.createElement("div")
div.className = 'light'
div.innerText=''
div.style.backgroundColor = ''
div.align = 'center'
div.style.fontSize = '30px'
div.style.lineHeight = '100px'
div.style.color = '#fff'
div.style.height = 100
div.style.width = 100
div.style.borderRadius = '50px'
document.body.appendChild(div)
var sleep = function (duration) {
return new Promise(function(resolve, reject) {
setTimeout(resolve,duration);
})
}
// 绿灯
var green = function () {
document.querySelector('.light').style.backgroundColor = 'green'
sleep(3000).then(()=> { yellow() });
}
// 黄灯
var yellow = function () {
document.querySelector('.light').style.backgroundColor = 'yellow'
sleep(1000).then(()=> { red() });
}
// 红灯
var red = function () {
document.querySelector('.light').style.backgroundColor = 'red'
sleep(2000).then(()=> { green() });
}
var init = function() {
// 绿灯启动
green()
}
// 执行
init()
// 找出所有具有 Symbol.iterator 的原生对象,并且看看它们的 for of 遍历行为。
Object.getOwnPropertyNames(window).filter(prop => {
return window[prop] && window[prop].prototype && window[prop].prototype[Symbol.iterator]
})
以上是关于javascript 重学前端系列的主要内容,如果未能解决你的问题,请参考以下文章