forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshim-sniffing.html
More file actions
76 lines (64 loc) · 1.72 KB
/
shim-sniffing.html
File metadata and controls
76 lines (64 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Shim Sniffing
* Description:
*/
// antipattern
Array.prototype.map = function() {
// stuff
};
// better
if (!Array.prototype.map) {
Array.prototype.map = function() {
// stuff
};
}
// even better
if (typeof Array.prototype.map !== "function") {
Array.prototype.map = function() {
// stuff
}
}
// If use either native or your own implementation, but not others:
// When you call toString() of a native function it should return a string with a function that has a body of [native code]
// by default there is white spaces and new lines issue
console.log(Array.prototype.map.toString().replace(/\s/g, '*'));
// "*function*map()*{*****[native*code]*}*" // IE
// "function*map()*{*****[native*code]*}" // FF
// "function*map()*{*[native*code]*}" // Chrome
// a proper check can fix the problem
console.log(Array.prototype.map.toString().replace(/\s/g, ''));
// "functionmap(){[nativecode]}"
// a reusable shim() function
function shim(o, prop, fn) {
var nbody = "function" + prop + "(){[nativecode]}";
if (o.hasOwnProperty(prop) &&
o[prop].toString().replace(/\s/g, '') === nbody) {
// native!
return true;
}
// shim
o[prop] = fn;
}
// this is native, cool
shim(
Array.prototype, 'map',
function(){/*...*/}
); // true
// this is new
shim(
Array.prototype, 'mapzer',
function(){console.log(this)}
);
[1,2,3].mapzer(); // alerts 1,2,3
// References
// http://www.jspatterns.com/shim-sniffing/
</script>
</body>
</html>