You are on page 1of 16

5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

You have 2 free stories left this month. Sign up and get an extra one for free.

5 JavaScript Tips I Learned From Vue


Source Code
Learn JavaScript from the source code of the popular JS frameworks.

bit sh Follow
May 15 · 5 min read

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 1/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

Photo by Caspar Camille Rubin on Unsplash

We know that reading the source code of well-known frameworks can


effectively improve the programming level. I recently read vue2.x source
code and learned a lot of JS related tips. Then I wrote this article, I hope it
will help you.

1. Determine the specific type of any object


As we all know, there are six primitive data types(Boolean, Number, String,
Null, Undefined, Symbol) and an object data type in JavaScript. But do you
know that the object data type can be subdivided into many seed types? An
object may be an array, function, map, etc. If we want to get the specific
type of object, what should we do?

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 2/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

Before we get into that, let’s look at another question:

What is the difference between


Object.prototype.toString.call(arg) and
String(arg) ?

Both expressions attempt to convert a parameter to a string, but there is a


difference between them.

String(arg) will try to call arg.toString() or arg.valueOf() , so if arg or

arg prototype rewrite the two methods, the


Object.prototype.toString.call(arg) and String(arg) will get different
results.

const _toString = Object.prototype.toString


var obj = {}

obj.toString() // [object Object]


_toString.call(obj) // [object Object]

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 3/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

In this case, String(arg) and Object.prototype.toString.call(arg) have


the same effect.

const _toString = Object.prototype.toString


var obj = {}

obj.toString = () => '111'

obj.toString() // 111
_toString.call(obj) // [object Object]

/hello/.toString() // /hello/
_toString.call(/hello/) // [object RegExp]

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 4/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

In this case, String(arg) and Object.prototype.toString.call(arg) have a


different result.

The ECMAScript has the following rules:

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 5/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

From EcmaScript

For different objects, different results will be returned when calling


Object.prototype.toString().

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 6/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

Moreover, the return value of Object.prototype.toString() is always in the


format of ‘[object ’ + ‘tag’ +‘] ’. If we only want the middle tag, We can
delete characters on both sides by regular expression or
String.prototype.slice().

function toRawType (value) {


const _toString = Object.prototype.toString
return _toString.call(value).slice(8, -1)
}

toRawType(null) // "Null"
toRawType(/sdfsd/) //"RegExp"

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 7/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

With the above function, we can get the type of a JavaScript variable.

You can find this function is Vue source code at:

vuejs/vue
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework
for building UI on the web. - vuejs/vue
github.com

(line 62)

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 8/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

2. Caching function calculation results


If there is such a function:

function computed(str) {
// Suppose the calculation in the funtion is very time consuming
console.log('2000s have passed')
return 'a result'
}

We want to cache the result of the function operation. When it is called


later, if the parameters are the same, the function will no longer be
executed, but the result in the cache will be returned directly. What can we
do?

We can write a cached function to wrap around our target function. This
cache function takes the target function as an argument and returns a new
wrapped function. Inside the cached function, we can cache the result of
the previous function call with an Object or Map .

1 function cached(fn){
2 // Create an object to store the results returned after each function execution.
3 const cache = Object.create(null);
4
5 // Returns the wrapped function
https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 9/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

6 return function cachedFn (str) {


7
8 // If the cache is not hit, the function will be executed
9 if ( !cache[str] ) {
10 let result = fn(str);
11
12 // Store the result of the function execution in the cache
13 cache[str] = result;
14 }
15
16 return cache[str]
17 }
18 }

cache.js hosted with ❤ by GitHub view raw

Here is an example:

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 10/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

You can find this function is Vue source code at:

vuejs/vue
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework
for building UI on the web. - vuejs/vue
github.com

(line 153)

3. Convert the hello-world style to the helloWorld


style
When we need to collaborate on large projects, a common code style is
necessary. Some people might be used to writing helloWorld , some people

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 11/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

might be used to writing hello-world . To solve this problem, we can write a

function that uniformly converts hello-world to helloWorld .

const camelizeRE = /-(\w)/g

const camelize = cached((str) => {


return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})

camelize('hello-world')
// "helloWorld"

vuejs/vue
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework
for building UI on the web. - vuejs/vue
github.com

(line 164)

4. Determine the JS running environment

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 12/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

Today, with the rapid development of the front end, our JavaScript code
may be executed in different runtime environments. In order to better adapt
to the various runtime environments, we need to determine which runtime
environment the current code is executing in. Let’s take a look at how Vue
determines the running environment:

1 const inBrowser = typeof window !== 'undefined'


2 const inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform
3 const weexPlatform = inWeex && WXEnvironment.platform.toLowerCase()
4 const UA = inBrowser && window.navigator.userAgent.toLowerCase()
5 const isIE = UA && /msie|trident/.test(UA)
6 const isIE9 = UA && UA.indexOf('msie 9.0') > 0
7 const isEdge = UA && UA.indexOf('edge/') > 0
8 const isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android')
9 const isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios')
10 const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge
11 const isPhantomJS = UA && /phantomjs/.test(UA)
12 const isFF = UA && UA.match(/firefox\/(\d+)/)

v.js hosted with ❤ by GitHub view raw

You can find this function is Vue source code at:

vuejs/vue
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework
for building UI on the web. - vuejs/vue
github.com
https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 13/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

(line 6)

5. Determines whether a function is native or user-


defined
As we know, there are two types of functions in JavaScript, one provided by
the host environment and the other customized by the user. The two
functions have different results when they are converted to strings.

Array.isArray.toString() // "function isArray() { [native code] }"

function fn(){}
fn.toString() // "function fn(){}"

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 14/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

The result of the native function toString is always in function fnName() {

[native code] } format. We can use this to distinguish them.

1 function isNative (Ctor){


2 return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
3 }

v.js hosted with ❤ by GitHub view raw

You can find this function is Vue source code at:

vuejs/vue
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework
for building UI on the web. - vuejs/vue
github.com

(line 58)

JavaScript Vuejs Web Development Programming Vue

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 15/16
5/24/2020 5 JavaScript Tips I Learned From Vue Source Code - Level Up Coding

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. Follow all the topics you care about, and Get unlimited access to the best stories
On Medium, smart voices and original we’ll deliver the best stories for you to on Medium — and support writers while
ideas take center stage - with no ads in your homepage and inbox. Explore you’re at it. Just $5/month. Upgrade
sight. Watch

About Help Legal

https://levelup.gitconnected.com/5-javascript-tips-i-learned-from-vue-source-code-6095df4e9bc1 16/16

You might also like