class MyClass{
constructor(){
}
get prop(){
return 'getter';
}
set prop(value){
console.log('setter: '+value);
}
}
let inst=new MyClass();
inst.prop=123;
console.log(inst.prop)
class Logger{
constructor(){//简单的解决方法时,在构造方法中绑定this.这样就不会找不到print方法了.
this.printName=this.printName.bind(this);
}
printName(name='there'){
this.print(`Hello ${name}`);
}
print(text){
console.log(text);
}
}
const logger=new Logger();
const {printName}=logger;
printName();
//------静态方法----------------//
class Foo{
static classMethod(){
return 'hello';
}
}
console.log(Foo.classMethod());
let foo=new Foo();
//foo.classMethod();//foo.classMethod is not a function
//父类的静态方法可以被子类继承
class Bar extends Foo{
}
console.log(Bar.classMethod())
//-------new target---------------//
//new 是从构造函数生成实例对象的命令. ES6为new命令引入了一个new.target属性,该属性
//一般用在构造函数中,返回new命令作用于的那个构造函数,如果构造函数不是通过new命令或者
//Reflect.construct()调用的,new.target会返回undefined
class Person{
constructor(name){
if(new.target===undefined){
throw new Error('必须使用new命令生成实例')
}
this.name=name;
}
}
// function Person(name) {
// if (new.target !== undefined) {
// this.name = name;
// } else {
// throw new Error('必须使用 new 命令生成实例');
// }
// }
var person=new Person('zhangsan');
var notAPerson=Person.call(person,'lisi');
//如果是用class关键字 那么直接就会报错. 无需使用new.target属性.
console