1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > JS高级 - 面向对象3(面向过程改写面向对象)

JS高级 - 面向对象3(面向过程改写面向对象)

时间:2019-08-10 00:26:25

相关推荐

JS高级 - 面向对象3(面向过程改写面向对象)

改写:

1.前提:所有东西都在onload

2.改写:不能有函数嵌套,可以有全局变量

onload --> 构造函数

全局变量 --> 属性

函数 --> 方法

4.改错: this

this啥时候会出问题?

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.事件

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。