JavaScript中es6中的class和class的继承(二)

4 篇文章 0 订阅
3 篇文章 0 订阅

class 类中常用的关键字

  1. static
  2. get
  3. 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();


JavaScript中es6中的class和class的继承(三)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值