1.第一种调用方法:obj[Reflect.ownKeys(obj)[index]]()
//向对象中添加方法 up down
let game = {
name: 'YY',
up() {
console.log('向上');
},
down() {
console.log('向下');
}
}
//声明一个对象
let methods = {
up: Symbol(),
down: Symbol()
};
game[methods.up] = function() {
console.log('up');
}
game[methods.down] = function() {
console.log('down');
}
console.log(game);
game.up(); //向上
game.down(); //向下
//调用Symbol创建的函数
game[Reflect.ownKeys(game)[3]]() //up
game[Reflect.ownKeys(game)[4]]() //down
2.第二种调用方法:Object.getOwnPropertySymbols(obj)[index]();
//直接加入
let youxi = {
name: '狼人杀',
[Symbol('say')]: function() {
console.log('发言');
},
[Symbol('zibao')]() {
console.log('自爆');
}
}
console.log(youxi);
console.log(youxi['name']); //狼人杀
//调用Symbol创建的函数
const a = Object.getOwnPropertySymbols(youxi);
youxi[a[0]](); // 发言
youxi[a[1]](); // 自爆
3.第三种方法调用:obj[方法名]()
let up1 = Symbol();
let down1 = Symbol();
let game1 = {
name: 'YY',
up1() {
console.log(1);
},
down1() {
console.log(2);
},
[up1]() {
console.log('向上');
},
[down1]() {
console.log('向下');
}
}
console.log(game1);
game1.up1(); // 1
game1.down1(); // 2
//调用Symbol创建的函数
game1[up1](); // 向上
game1[down1](); // 向下