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

posted @ 2017-10-05 01:01  【唐】三三  阅读(181)  评论(0编辑  收藏  举报