Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods learned from the Vue.js source code

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what are the methods learned from the Vue.js source code?" in the operation of actual cases, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Immediately execute the setting function that is executed only once after the function page has been loaded.

(function (a, b) {console.log (a, b); / / 1Magol 2})

Typically, the global variable is passed as a parameter to the immediate execution parameter so that it can be accessed inside the function without using window.

(function (global) {console.log (global); / / Window object}) (this)

Multi-layer nested trinocular operation

Because of the nesting of ternary operators, the readability of the code is poor, which can be used in simple business scenarios.

Var a = 1; var b = 0; a = = 1? (B = = 2? (B = 3): (B = 1)): "; console.log (b); / / 1

Freeze object

You cannot add, delete or modify the specified object.

Var emptyObject = Object.freeze ({key: "1",}); emptyObject.name = "maomin"; delete emptyObject.key; emptyObject.key = "2"; console.log (emptyObject)

Sealed object

Only changes can be made to the specified object, not add and delete operations.

Var sealObject = Object.seal ({key: 3,}); sealObject.name = "maomin"; delete sealObject.key; sealObject.key = 4; console.log (sealObject); / / 4

Check to see if it is the original value

Function isPrimitive (value) {return (typeof value = = "string" | | typeof value = = "number" | | / / $flow-disable-line typeof value = "symbol" | | typeof value = "boolean");}

Quickly detect whether it is an object

When we know the original value, it is mainly used to distinguish the object from the original value.

Function isObject (obj) {return obj! = = null & & typeof obj = "object";} console.log (isObject (true)); / / false

Detect target type

Var _ toString = Object.prototype.toString; function toRawType (value) {return _ toString.call (value) .slice (8,-1);} console.log (toRawType ([])); / / Array

Check whether the target is a valid array index

Function isValidArrayIndex (val) {var n = parseFloat (String (val)); return n > = 0 & & Math.floor (n) = = n & & isFinite (val);}

Detect whether it is a Promise object

Function isDef (v) {return v! = = undefined & & v! = = null;} function isPromise (val) {return (isDef (val) & & typeof val.then = "function" & & typeof val.catch = "function");} var promiseObj = new Promise (function (resolve, reject) {/ / a time-consuming asynchronous operation resolve ("success") / / data processing completed / / reject ('failure') / / data processing error}). Then ((res) = > {console.log (res);}, / success (err) = > {console.log (err);} / / failure); console.log (isPromise (promiseObj)); / / true

Convert the target to a string

Var _ toString = Object.prototype.toString; function isPlainObject (obj) {return _ toString.call (obj) = = "[object Object]";} function toString (val) {return val = = null? ": Array.isArray (val) | | (isPlainObject (val) & & val.toString = _ toString)? JSON.stringify (val, null, 2): String (val);} console.log (toString ({name: 1})); / / {"name": 1}

Convert to a number

Converts input values to numbers for persistence. If the conversion fails, the original string is returned.

Function toNumber (val) {var n = parseFloat (val); return isNaN (n)? Val: n;}

Detect whether key is within the created Map object

Function makeMap (str, expectsLowerCase) {var map = Object.create (null); var list = str.split (","); for (var I = 0; I

< list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; }; } var isbuiltInTag = makeMap("slot,component", true); console.log(isbuiltInTag("component")); // true 删除简单数组中某一项 function remove(arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index >

-1) {return arr.splice (index, 1);}} console.log (remove ([1,2], 1)); / / [1]

Detect whether there is a specified key in the object

Var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) {return hasOwnProperty.call (obj, key);} console.log (hasOwn ({name: 1}, "name")); / / true

Convert a class array object to a real array

Function toArray (list, start) {start = start | | 0; var I = list.length-start; var ret = new Array (I); while (I -) {ret [I] = list [I + start];} return ret;} console.log (toArray ({0: 42,1: 52,2: 63, length: 3}); / [42,52,63]

Blend attributes into the target object

Function extend (to, _ from) {for (var key in _ from) {to [key] = _ name1:2 [key];} return to;} console.log (extend ({name:1}, {name1:2})); / / {name:1,name1:2}

Merge an array of objects into a single object

Function extend (to, _ from) {for (var key in _ from) {to [key] = _ from [key];} return to;} function toObject (arr) {var res = {}; for (var I = 0; I

< arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res; } console.log(toObject([{ name: 1 }, { name: 1 }, { name: 2 }, { name1: 3 }])); // {name: 2, name1: 3} 检测指定项在数组(简单数组、数组对象)中的索引 function isObject(obj) { return obj !== null && typeof obj === "object"; } function looseEqual(a, b) { if (a === b) { return true; } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return ( a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]); }) ); } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysb = Object.keys(b); return ( keysA.length === keysb.length && keysA.every(function (key) { return looseEqual(a[key], b[key]); }) ); } else { /* istanbul ignore next */ return false; } } catch (e) { /* istanbul ignore next */ return false; } } else if (!isObjectA && !isObjectB) { return String(a) === String(b); } else { return false; } } function looseIndexOf(arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i; } } return -1; } console.log(looseIndexOf([{ name: 1 }, { name: 2 }], 4)); // -1 console.log(looseIndexOf([{ name: 1 }, { name: 2 }], { name: 1 })); // 0 确保函数只调用一次 function once(fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } }; } var callOnce = once(function () { console.log("javascript"); }); callOnce(); // javascript callOnce(); 定义对象属性 如果你想禁止一个对象添加新属性并且保留已有属性,就可以使用Object.preventExtensions(obj)。 function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, // 对象定义属性 enumerable: !!enumerable, // 描述属性是否会出现在for in 或者 Object.keys()的遍历中 writable: true, // 是否可写 configurable: true, // 是否重新定义或者删除 }); } var obj = { name: 1, }; def(obj, "name1", 2, true); obj.name1 = 3; console.log(obj); // {name: 1, name1: 3} 浏览器环境嗅探 var inBrowser = typeof window !== "undefined"; var inWeex = typeof WXEnvironment !== "undefined" && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf("msie 9.0") >

0; var isEdge = UA & & UA.indexOf ("edge/") > 0; var isAndroid = (UA & & UA.indexOf ("android") > 0) | | weexPlatform = "android"; var isIOS = (UA & & / iphone | ipad | ipod | ios/.test (UA)) | weexPlatform = = "ios"; var isChrome = UA & / chrome\ /\ d+/.test (UA) & & isEdge; var isPhantomJS = UA & & / phantomjs/.test (UA); var isFF = UA & & UA.match (/ firefox\ / (\ d+) /)

Comparison between the methods in the JS constructor and the methods on the constructor prototype attribute

The method defined inside the constructor will clone it on each instance of it; the method defined on the prototype property of the constructor will make the method shared by all its examples, but will not be redefined inside each instance. If our application needs to create a lot of new objects, and there are many methods for these objects, to save memory, we recommend defining these methods on the prototype property of the constructor. Of course, in some cases, we need to define certain methods in the constructor, usually because we need to access private variables within the constructor.

Function A () {this.say = function () {console.log (1);} var a = new A (); a.say (); function B () {} B.prototype.say = function () {console.log (2);}; var b = new B (); b.say (); var c = new B (); c.say ()

Get tag content (including tags)

Function getOuterHTML (el) {if (el.outerHTML) {return el.outerHTML;} else {var container = document.createElement ("div"); container.appendChild (el.cloneNode (true)); return container [XSS _ clean];}}

String hash value

Function hash (str) {var hash = 5381; var I = str.length; while (I) {hash = (hash * 33) ^ str.charCodeAt (--I);} return hash > 0;} console.log (hash ("222sd")); / / 164533792 "what are the methods learned from the Vue.js source code" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report