Good evening,
I have been trying to wrap my head about this, below, code written by Chris Coyer.
I understand this is a self-invoked function named 'supports', but what I don't understand is how 'supports' is passed an argument (as seen below in the // Test section). Please could someone explain this or point me in the right direction for further reading?
// Generic Testing Function
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
return true;
}
}
return false;
};
})();
// Test
if ( supports('flowInto') ) {
$("html").addClass('cssregions');
} else {
$("html").addClass('no-cssregions');
}
Let's see what supports
is:
var supports = (function() {
/* ... */
})();
OK, so supports
is the return value of an anonymous function that gets invoked on the spot. What does this anonymous function return?
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
return true;
}
}
return false;
};
Alright, so the return value of this function (which is what support
holds as we said above) is actually a function that takes one argument ( prop
).
So at this point it should become clear that it's perfectly logical to do what the test section does, ie call that function:
if ( supports('flowInto') ) /* .... */
It's really not complicated when you know where to start from.
The self-invoking function is returning a function, which accepts an argument.
So, the SIF gets executed, returns
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
return true;
}
}
return false;
};
this guy here. And this function reference is stored into the supports
variable.
supports
is the function returned by the anonymous, self-invoking function (this one):
function(prop) {
if (prop in div.style) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while (len--) {
if (vendors[len] + prop in div.style) {
return true;
}
}
return false;
};
So the argument-passing in question passes the prop
argument.
That's a self-invoking function that returns a function .
supports
is assigned the the function that the self-invoking function returns.
变量“ supports”正在接收新功能,可以在行中看到
return function(prop) {
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.