• 面向对象中this问题


    this什么时候会出错?

      注意:其中var _this = this 的巧妙用法。

      1.定时器;

      

    <script type="text/javascript">
        //如果面向对象中用了定时器
        function Aaa() {
            var _this = this;
            this.a=12;
    //        setInterval(this.show,1000)//凡事用定时器调的函数,他的this必然是window。
            //解决方法:再套一层,注意用this。
            setInterval(function () {
                _this.show();
            },1000)
        }
        Aaa.prototype.show = function () {
            console.log(this.a);
        }
        var obj = new Aaa();
        obj.show();
    </script>

      2.事件;

      

    <script type="text/javascript">
        function Bbb() {
            var _this = this;//用this取到对象
            this.b=5;
            //如果面向对象中用了事件
            document.getElementById("btn1").onclick = function () {
                _this.show();
            }
        }
        Bbb.prototype.show = function () {
            console.log(this.b);
        }
        window.onload = function () {
            new Bbb();
        }
    </script>
  • 相关阅读:
    CDN 机制
    canvas绘制旋转图形
    前端资源网站
    css中的em用法
    响应式网页设计【转载】
    闭包与非闭包
    跨域文档之间的访问
    ajax跨域之---服务器端代理实现
    jsonp跨域实现
    freemarker 命名空间
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/6047711.html
Copyright © 2020-2023  润新知