zoukankan      html  css  js  c++  java
  • 19-class的基本语法

      1、class用来干嘛的?

    答:通过class关键字可以定义类。

    2、constructor和this代表什么?

    答:constructor代表构造方法。this关键字代表实例对象。声明class的语法如下,注意没有小括号()。

    class Point {
        constructor(x,y) {
            this.x = x;
            this.y = y;
        }
        
        toString() {
            return `(${this.x} 与 ${this.y})`
        }
    }

    3、定义类方法的时候需要注意什么?

    答:前面不要加function关键字,方法之间不能用逗号隔开,否则报错。

    4、类的数据类型是什么?

    答:函数。用typeof检验类型为function。

    5、类是怎么使用的?

    答:类和模块的内部默认使用严格模式。声明一个类需要使用new关键字。

    class Point {
        doStuff(){
            console.log(111)
        }
    }
    
    let test = new Point();
    test.doStuff();

     6、constructor是什么,他默认返回的是什么?

    答:constructor是类的默认方法。一个类必须有constructor方法,如果没有定义,一个空的constructor方法会被默认添加。

    constructor默认返回的是实例对象,即this。

    7、类与普通函数的区别是什么?

    答:类必须使用new来调用,否则报错。普通函数不使用new也可以执行。

    8、类的this的指向是什么?要想在类的外面使用类里面的方法,怎么办?

    答:类里面的this指向的是类的实例。但是一旦在类的外面使用了this,就会报错。

    class Logger {
        printName(name = 'there') {
            this.print(`Hello ${name}`)
        }
    }
    const logger = new Logger();
    logger.printName(); //Hello there
    
    const {printName} = logger;
    printName(); //TypeError: Cannot read property 'print' of undefined

      

    要想在类的外面使用类里面的方法,有两种解决方法,一是在构造方法中绑定this,二是使用箭头函数(在constructor里面定义,没用到过,不讲了)。

    class Logger {
        constructor(){
            this.printName = this.printName.bind(this)
        }    
        printName(name = 'there') {
            this.print(`Hello ${name}`)
        }
    }
    
    const logger = new Logger();
    const {printName} = logger;
    printName(); //Hello there

    9、类是否存在变量提升?

    答:类不存在变量提升,因此必须先声明,后使用。

    10、什么是静态方法?

    答:类相当于实例的原型,所有在类中定义的方法都会被实例继承。如果在一个方法前面加上static关键字,就表示该方法不会被实例继承,而是通过类才能调用,这称为“静态方法”。

    class Foo{
        static method(){
            console.log("hello")
        }
    }
    Foo.method(); //hello
    
    var foo = new Foo();
    foo.classMethod(); //TypeError: foo.classMethod is not a function 

    11、那么父类里的静态方法是被谁继承?

    答:父类里的静态方法可以被子类继承。

    class Foo{
        static method(){
            console.log("hello")
        }
    }
    class Bar extends Foo{
    }
    Bar.method() //hello

      

  • 相关阅读:
    主流浏览器默认限制的非安全端口号有哪些
    coco2dx实现翻拍效果
    iOS和android游戏纹理优化和内存优化(cocos2d-x)(转载)
    cocos2d-x如何解决图片显示模糊问题
    cocos2dx混合模式应用———制作新手引导高亮区域
    visual studio的项目属性表
    如何提高cocos2d-x-spine骨骼动画加载速度
    如何调试lua脚本
    把.pvr.ccz文件转换成png
    coco2dx加载网络图片并保存
  • 原文地址:https://www.cnblogs.com/qingshanyici/p/11063129.html
Copyright © 2011-2022 走看看