改写:
1.前提:所有东西都在 onload
里
2.改写:不能有函数嵌套,可以有全局变量
onload --> 构造函数
全局变量 --> 属性
函数 --> 方法
4.改错: thisthis
啥时候会出问题?
1.定时器
<script>function Aar() {this.a = 12;setInterval(this.show, 1000); //这里的this 是window}Aar.prototype.show = function() {console.log(this.a); };var obj = new Aar();//obj.show(); //12</script></script>
定时器调用的this
是指window
。
解决方法:再套一层
<script>function Aar() {var _this = this; //obj对象this.a = 12;// setInterval(this.show, 1000); //这里的this 是windowsetInterval(function() { _this.show() }, 1000); //这里调用_this(obj对象)}Aar.prototype.show = function() {console.log(this.a); };var obj = new Aar();//obj.show(); //12</script>
2.事件