zoukankan      html  css  js  c++  java
  • 9.使用类的2个注意点

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    
    <body>
        <button>点击</button>
        <script>
            var that;
            var _that;
            class Star {
                constructor(uname, age) {
                    // constructor 里面的this 指向的是 创建的实例对象
                    that = this;
                    console.log(this);
    
                    this.uname = uname;
                    this.age = age;
                    // this.sing();
                    this.btn = document.querySelector('button');
                    this.btn.onclick = this.sing;
                }
                sing() {
                    // 这个sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
                    console.log(this);
    
                    console.log(that.uname); // that里面存储的是constructor里面的this
                }
                dance() {
                    // 这个dance里面的this 指向的是实例对象 ldh 因为ldh 调用了这个函数
                    _that = this;
                    console.log(this);
    
                }
            }
    
            var ldh = new Star('刘德华');
            console.log(that === ldh);
            ldh.dance();
            console.log(_that === ldh);
    
            // 1. 在 ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象
    
            // 2. 类里面的共有的属性和方法一定要加this使用.
        </script>
    </body>
    
    </html
  • 相关阅读:
    创建可管理的对象属性
    解析简单xml文档
    定义类的__slots__属性节省内存的开销
    读写json数据
    读写csv,excel文件数据
    常用的字符串处理方法
    sql中case when 的使用
    对字典的处理
    元组的元素命名
    列表,字典,集合按条件筛选
  • 原文地址:https://www.cnblogs.com/juham/p/14703411.html
Copyright © 2011-2022 走看看