6. 扩展的对象功能

126 阅读1分钟

es6直接写入变量和函数,作为对象的属性和方法

const name = 'Max',
      age = 23;
const person = {
    name: name,
    age: age,
    sayName: function(){
        
    }
}
//es中简写方式:属性名和引入的变量名一样,可以简写
const name = 'Max',
      age = 23;
const person = {
    name,
    age,
    sayName(){
        console.log(this.name)
    }
} 
person.sayName();//Max

用法示例

取值器/设值器

let car = {
    wheel: 4,
    set(newVal) {
        if (newVal < this.wheel) {
            throw new Error('轮子数太少')
        }
        this.wheel = newVal;
    },
    get() {
        return this.wheel;
    }
}
console.log(car.get());//取值
car.set(7)//设值
console.log(car.get());//取值

从对象外部引入一个变量,让对象内部的变量名和函数名根据引入的变量值来改变

const name = 'Max';
const obj = {
    isShow: true,
    [name + '-age']: 23,
    ['fn-' + name]() {
        console.log(this);
    }
}
console.log(obj);//{isShow: true, Max-age: 23, fn-Max: ƒ}