Problem Description: I wrote a function class. In the prototype, there is an attribute (value is a function) to judge the platform. In order to optimize, I thought of using function self execution and closure to make multiple operations only need to go through the judgment process once. The problem is that I thought of another way (Curiosity Kills the cat): the function changes itself internally, then calls itself once, and then When this function is called, it directly calls the changed value to achieve the optimization effect. However, there is a problem. Later, after debug ging with colleagues for many times, we found the problem (thief low's problem). However, when looking back, we thought about the problem first and thought about the function promotion. Here is an error example. If you are interested, you can see where the error is( It's more intuitive to change the way of writing...
show you the key code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
</style>
</head>
<body>
<button id="seeBug">Point me and explode</button>
<script type="text/javascript">
/**----------Test case----------- */
function Func(){
}
Func.prototype = {
bindEvent: function init(){
document.getElementById('seeBug').addEventListener('click', function(){
this.share();
}.bind(this), false);
},
platform: function platform(){
var agent = navigator.userAgent;
// Judge wechat
if (!/MicroMessenger/.test(agent)) {
if (/iPhone/.test(agent)) {
// Judge iPhone X
if (screen.height !== 812) {
this.platform = function() {
return 'iPhoneX';
};
} else {
this.platform = function() {
return 'iPhone';
};
}
// Judge Android
} else if (/Android/.test(agent)) {
this.platform = function() {
return 'Android';
};
} else {
this.platform = function() {
return 'other';
};
}
} else {
this.platform = function() {
return 'wx';
};
}
this.platform();
},
share: function share(){
var _platform = this.platform();
console.log(_platform);
}
}
new Func().bindEvent();
/**--------------------- */
</script>
</body>
</html>