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

 

 

  

posted @ 2019-11-03 22:44  qingshanyici  阅读(171)  评论(0编辑  收藏  举报