您的位置:首页 > Web前端 > JavaScript

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

2017-10-05 01:01 239 查看
改写:

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 是window
setInterval(function() {
_this.show()
}, 1000);       //这里调用_this(obj对象)
}
Aar.prototype.show = function() {
console.log(this.a);
};
var obj = new Aar();
//obj.show(); //12
</script>

2.事件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: