Skip to content

Commit d24cefd

Browse files
committed
added shim sniffing to general patterns
1 parent 88825c2 commit d24cefd

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<!doctype html>
2+
<htmllang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<metacharset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
/* Title: Shim Sniffing
10+
* Description:
11+
*/
12+
13+
// antipattern
14+
Array.prototype.map=function(){
15+
// stuff
16+
};
17+
18+
if(!Array.prototype.map){
19+
Array.prototype.map=function(){
20+
// stuff
21+
};
22+
}
23+
24+
if(typeofArray.prototype.map!=="function"){
25+
Array.prototype.map=function(){
26+
// stuff
27+
}
28+
}
29+
30+
// browsers seem to be a little frivolous with white spaces and new lines
31+
console.log(Array.prototype.map.toString().replace(/\s/g,'*'));
32+
// "*function*map()*{*****[native*code]*}*" // IE
33+
// "function*map()*{*****[native*code]*}" // FF
34+
// "function*map()*{*[native*code]*}" // Chrome
35+
36+
console.log(Array.prototype.map.toString().replace(/\s/g,''));
37+
// "functionmap(){[nativecode]}"
38+
39+
functionshim(o,prop,fn){
40+
varnbody="function"+prop+"(){nativecode]}";
41+
if(o.hasOwnProperty(prop)&&
42+
o[prop].toString().replace(/\s/g,'')===nbody){
43+
// native!
44+
returntrue;
45+
}
46+
// shim
47+
o[prop]=fn;
48+
}
49+
50+
// this is native, cool
51+
shim(
52+
Array.prototype,'map',
53+
function(){/*...*/}
54+
);// true
55+
56+
// this is new
57+
shim(
58+
Array.prototype,'mapzer',
59+
function(){console.log(this)}
60+
);
61+
62+
[1,2,3].mapzer();// alerts 1,2,3
63+
64+
// References
65+
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
66+
</script>
67+
</body>
68+
</html>

0 commit comments

Comments
(0)