TypeError: Cannot read properties of undefined (reading 'a')
TypeError: Cannot read properties of undefined (reading 'a')
我正在尝试 类 和 Javascript 中的 this 关键字,我写了这段代码:
class p{
constructor(p,a){
p = p.p;
a = p.a;
};
};
const c = new p(p="1st aspect",a="2nd aspect");
console.log(this.c);
我得到了这个错误:
Cannot read properties of undefined (reading 'a')
我不知道这是否与 类 兼容,或者我是否传递了错误的参数,有人可以帮助我吗?
创建 class 的语法错误。您不需要传递参数名称。只需使用
const c = new p("1st aspect","2nd aspect");
使用小写首字母作为 class 名字不是好的做法。使用 P
而不是 p
。而 this.c
是错误的。只需打印
console.log(c);
这只是您用于创建 class 实例的语法在尝试使用提供的参数名称(“p =”、“a =”)方面不正确,并且可能您的 class 构造中存在一些错误。我想你可能一直在尝试做这样的事情:
class p {
// These are ordered arguments, not named arguments
constructor(p,a) {
// Save the value of p and a on the class instance
this.p = p;
this.a = a;
};
};
// Create a new p class instance with the arguments in order
const classInstance = new p("1st aspect", "2nd aspect");
代码应该如下所示
class P {
constructor(p, a){
this.p = p;
this.a = a;
};
};
const c = new P("1st aspect", "2nd aspect");
console.log(c); // <- just print c
我看得出您混淆了一些概念并感到困惑,我建议您阅读 official MDN Docs,您将逐步了解 classes。
另外,您会注意到 class 个名称是使用 PascalCase 命名的。这是因为通过遵循命名约定,您将更快地阅读和理解其他人的代码(甚至是您的代码)。
希望对您有所帮助!
我正在尝试 类 和 Javascript 中的 this 关键字,我写了这段代码:
class p{
constructor(p,a){
p = p.p;
a = p.a;
};
};
const c = new p(p="1st aspect",a="2nd aspect");
console.log(this.c);
我得到了这个错误:
Cannot read properties of undefined (reading 'a')
我不知道这是否与 类 兼容,或者我是否传递了错误的参数,有人可以帮助我吗?
创建 class 的语法错误。您不需要传递参数名称。只需使用
const c = new p("1st aspect","2nd aspect");
使用小写首字母作为 class 名字不是好的做法。使用 P
而不是 p
。而 this.c
是错误的。只需打印
console.log(c);
这只是您用于创建 class 实例的语法在尝试使用提供的参数名称(“p =”、“a =”)方面不正确,并且可能您的 class 构造中存在一些错误。我想你可能一直在尝试做这样的事情:
class p {
// These are ordered arguments, not named arguments
constructor(p,a) {
// Save the value of p and a on the class instance
this.p = p;
this.a = a;
};
};
// Create a new p class instance with the arguments in order
const classInstance = new p("1st aspect", "2nd aspect");
代码应该如下所示
class P {
constructor(p, a){
this.p = p;
this.a = a;
};
};
const c = new P("1st aspect", "2nd aspect");
console.log(c); // <- just print c
我看得出您混淆了一些概念并感到困惑,我建议您阅读 official MDN Docs,您将逐步了解 classes。
另外,您会注意到 class 个名称是使用 PascalCase 命名的。这是因为通过遵循命名约定,您将更快地阅读和理解其他人的代码(甚至是您的代码)。
希望对您有所帮助!