问题描述:我写了一个函数类,原型中有一个判断平台的属性(值为函数),为了优化我想到用函数自执行和闭包使得多次操作只需要走一次判断流程,这是没问题的,问题点是我想着撸了另一种方式(好奇心害死猫):函数内部改变自身,然后自调用一次,之后调用该函数时调用的便直接是改变后的值也能达到优化效果,然而,出了问题,后来和同事多次debug后发现了问题所在(贼low的问题啊···),不过回头一想当时找问题时先入为主,率先联想到了函数提升啥的,下面给出错误示例,有兴趣可以看看错在哪哦(改了一下写法,更直观)。。。
show you the key code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
</style>
</head>
<body>
<button id="seeBug">点我瞬间爆炸</button>
<script type="text/javascript">
/**----------测试用例----------- */
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;
// 判断微信端
if (!/MicroMessenger/.test(agent)) {
if (/iPhone/.test(agent)) {
// 判断iPhone X
if (screen.height !== 812) {
this.platform = function() {
return 'iPhoneX';
};
} else {
this.platform = function() {
return 'iPhone';
};
}
// 判断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>