ES6---class 类

Class ES6的新特性
 
 
class Vue {
    constructor(options) {
        this.getters={}
        this.a='a'
        Object.keys(options).forEach(name=>{
            Object.defineProperty(this.getters, name, {
                get: function(){
                    return `wzgl:${options[name]}`;
                }
            })
        })
    };
    finally(){
        console.log(this.a);
    }
}
let vm=new Vue({
    name: 'ml',
    age: '27'
})
console.log(vm.getters.name)
console.log(vm.getters.age)
console.log(vm.finally());

打印结果:

 其中:options为类内部传入的的项,

Object.defineProperty()

功能:方法会直接在一个对象上定义一个新属性,或修改一个对象的现有属性, 并返回这个对象。

语法: Object.defineProperty(obj, prop, descriptor)
obj:属性所在的对象
prop:目标对象需要定义或修改的属性的名称
descriptor:将被定义或修改的属性的描述符

例如:

Object.defineProperty(obj, 'key', { 
enumerable: false, //是否可枚举
configurable: false, //是否可以通过delete删除该属性 如:delete obj.name
writable: false, //是否可修改
value: 'static' })//设置的值

class是语法糖,其实现方法如下:

function Man(name, sex) {
    this.name = name;
    this.sec = sex;
}
Man.prototype.getName=function(){
    return this.name;
}
let person = new Man('ml', '18');
console.log(person.getName());
// -------ES6 的class写法------------
class Man{
    constructor(name,sex){
        this.name=name;
        this.sex=sex;
    }
    getName(){
        return this.name;
    }
}
let person2=new Man('ml','18');
console.log(person2.getName());
原文地址:https://www.cnblogs.com/alaner/p/15060251.html