【发布时间】:2020-11-18 15:05:28
【问题描述】:
我正在学习用窄函数类扩展 javascript 中的类。
在卡片类中: 我已经制作了一个静态对象,但我无法从对象信息中访问静态变量 this.number,恰好在“函数”中。
你能给我一种访问静态变量的方法吗?我不能改变对象的结构
放大问题:
static number = 44;
static info = {
name : "Games",
function(game){
console.log("fonction");
console.log("best card is "+game.best);
game.draw();
console.log(this.number); <======= CAN'T HAVE ACCES TO STATIC VARIABLE NUMBER
}
}
我打电话给:
President.info.function(partie1);
返回:
best card is 2 Heart
7 Heart
undefined
我还有一个问题,为什么“partie1.name()”会给我这个错误 “TypeError:partie1.name 不是函数” 整个代码
class Games {
constructor(name)
{
this.name = name;
this.joueurs = 2;
}
name(){
console.log(this.name);
}
nombre(){
console.log(this.joueurs);
}
}
let Cards = Base => class extends Base {
constructor(name){
super(name);
this.best = "King Heart";
}
static number = 44;
draw(){
console.log("7 Heart");
}
static info = {
name : "Games",
function(game){
console.log("fonction");
console.log("best card is "+game.best);
game.draw();
console.log(this.number);
}
}
}
let Dices = Base => class extends Base {
constructor(name){
this.name = name;
this.Dices = [1,2,3,4,5,6];
}
}
class President extends Cards(Games){
constructor(){
super("President");
this.best = "2 Heart";
}
static drawBest(game){
console.log(game.best);
}
}
let duel = new Games("duel");
duel.nombre(); // 2
let partie1 = new President();
President.drawBest(partie1);
//2 Heart
//partie1.name();
//TypeError: partie1.name is not a function
President.info.function(partie1);
// function
// best card is 2 Heart
// 7 Heart
// undefined ???
【问题讨论】:
-
我很困惑。为什么要从箭头函数返回类定义?
-
因为我可以扩展我的课堂游戏。 Game 是每个类的基础,如果我想创建纸牌游戏或骰子游戏,我可以用 Cards 或 Dice 扩展它
-
this是您调用.function方法的info对象。如果这不是您想要的,请不要嵌套对象。另一种方法是使用箭头函数,但实际上还不清楚info方法应该做什么,为什么将实例作为参数,以及为什么它不仅仅是一个简单的实例方法。 -
我无法更改结构,因为对象信息将是我所有班级的通用对象,只是具有不同的值,我在另一个文件中调用此信息对象。现在我明白为什么它不起作用但我怎样才能访问静态值?也许是出口?
标签: javascript function static