简体   繁体   English

为什么在类方法中使用我的实例属性时未定义?

[英]Why is my instance property undefined when used in a class method?

When trying to run cow1.voice(); 尝试运行cow1.voice(); and I keep getting an error in the console. 而且我在控制台中不断出现错误。

Uncaught ReferenceError: type is not defined 未捕获ReferenceError:类型未定义

class Cow {
  constructor(name, type, color) {
    this.name = name;
    this.type = type;
    this.color = color;
  };
  voice() {
    console.log(`Moooo ${name} Moooo ${type} Moooooo ${color}`);
  };
};

const cow1 = new Cow('ben', 'chicken', 'red');

type and others are instance variables of your class, so you need to use this to access them. type和其他type是类的实例变量,因此您需要使用this来访问它们。 The initial variables name , type , color , provided to the constructor are used for class initialisation and aren't available outside of constructor. 提供给构造函数的初始变量nametypecolor用于类的初始化,在构造函数之外不可用。

class Cow {
  constructor(name, type, color) {
    this.name = name;
    this.type = type;
    this.color = color;
  };

  voice() {
    // Access instance vars via this
    console.log(`Moooo ${this.name} Moooo ${this.type} Moooooo ${this.color}`);
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在类方法中使用时,类中的属性未定义 - Property in class is undefined when used in class method 为什么我的javascript类实例中的方法看不到属性 - Why can't a method in the instance of my javascript class see a property 为什么我的ES6(使用Babel)类在实例方法中未定义`this`? - Why does my ES6 (using Babel) class say `this` is undefined in an instance method? 使用该类的实例时,我的javascript类中的变量未定义 - variable in my javascript class is undefined when using an instance of that class 为什么在间隔循环中定时器实例中的属性未定义? - Why is property undefined in timer instance when in interval loop? 用作中间件时,此属性的属性未定义 - Property of this is undefined when used as Middleware 为什么在这个类方法中“this”未定义? - Why is “this” undefined in this class method? 为什么我在Typescript定义的类上的属性显示为未定义? - Why is a property on my Typescript-defined class showing up as undefined? Javascript - Class - 调用构造函数属性时返回未定义的方法 - Javascript - Class - Method Returning Undefined When Calling Constructor Property 使用方法调用时,Javascript类属性返回未定义 - Javascript class property return undefined when called with a method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM