简体   繁体   中英

MooTools 1.5.2 exploring typeOf and instanceOf

I decided to explore MooTools javascript core file to understand how such javascript frameworks work, unfortunately there are a lot of things in javascript that confuses me a lot because I don't know why particular function is made that way.

In the beginning of MooTools Core javascript file I see two functions: typeOf and instanceOf. I don't understand the purpose of these two lines of code:

var typeOf = this.typeOf = function(item){
var instanceOf = this.instanceOf = function(item, object){

Why function is assigned to typeOf variable and this.typeOf and why not just for var typeOf or just this.typeOf? And the same thing is with instanceOf.

I would be really grateful if anyone could explain why functions are assigned to variable and to global object what advantages can it give? I understand how it works but I simply can't understand why need to do it.

Doing var typeOf = this.typeOf has 3 purposes. One is to work with a small variable name inside the file and avoid using this.typeOf all the time, second and more important is to avoid mixing up scope inside a scope where this is something else. The third purpose, using this.typeOf is to export it to the scope where you are, and MooTools exports to global, ie the window object in the browser for example.

The function .typeOf is described in the docs and you can see it as a more usable method than the native typeof . Look at these diferences:

in MooTools:

typeOf([]) // gives you "array"
typeOf({}) // gives you "object"
typeOf(document.createElement('div')) // gives you "element"

in Native JavaScript

typeof [] // gives you "object"
typeof {} // gives you "object"
typeof document.createElement('div') // gives you "object"

So MooTools gives a much more valuable result. Similar behavior can be found in .instanceOf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM