class 类中常用的关键字
- static
- get
- set
static 关键字
static属于一个纯静态方法 只能通过类的关键字 去访问 该方法的位置
class Methods {
constructor(){
this.handleChange = this.handleChange(); //绑定到Methods
console.log(this.printName()); //Jack
console.log(Methods.Jack); //Jack
console.log(this.Jack); //undefined
//this----原型链上的↑↑↑ 绑定到Methods----上的↑↑↑
}
handleChange(){
return Methods.FunName;
}
printName = (name = Methods.Jack) => { //给一个默认值为‘Jack’
return name;
};
static FunName(){
console.log(this); //如果console.log(this),那么输出的是还未实例化的Methods方法的代码块
console.log(typeof this); //未实例化:object 实例化后 function
return 'handleChange';
}
static get Jack(){ //静态方法只能通过Method去访问
return 'Jack'
}
}
const methods = new Methods();
console.log(methods.handleChange() === Methods.FunName()); //true
console.log(Methods.FunName); //这里输出是的是一个function 可以被再次执行和调用
console.log(methods.FunName); // undefined
get 与 set
与Object.definedProproty里面的get或set类似
最大的区别就是 get 需要return 而 set 里面return是无效的
let str = 'nihao';
function block() {
class MyClass {
constructor() {
}
get prop() {
return 'nihao';
}
set prop(value) { //value 接受的就是改变的值
console.log(value);
// this.prop = value; 如果这句话使用的话那么就是 死循环
str = value;
}
}
class ParentClas extends MyClass{
constructor(){
super();
this.prop='haha'; //只有当get出来的值做出改变的时候 set才会生效
//此时 set props(value) 里面的value 是haha
}
}
let parentClass=new ParentClas(); //进行实例化
console.log('parentClass.prop:',parentClass.prop);
parentClass.prop="heihei";
//此时 set props(value) 里面的value 是heihei
console.log('parentClass.prop:',parentClass.prop);
console.log("str :", str);
//必须改变str get的props的值才能改变
}
block();
function block2() {
class Language {
constructor(type) { //undefined
this.type = type; //这里没有接收值 undefined
}
get info() {
return this.type;
}
set info(type) {
console.log(`set方法 :${type}`);
//set 里面使用return 方法是没用的 info 只能根据 它get 的值来改变
}
}
const test = new Language();
test.info = 'Python'; //只要info这个值一改变就会传入值
console.log(test.info);
}
block2();