如何在 JavaScript 类外部访问类属性

3

为什么这个 JavaScript 类中的声音属性没有被正确地设置为私有?此外,如何在类外访问它?我在视频中看到过并尝试在类外访问声音属性,但失败了。

class Dog {
  constructor() {
    this.sound = 'woof';
  }
  talk() {
    console.log(this.sound);
  }
}

谢谢!!

3个回答

6

这不是私有的,因为在创建类实例后可以从外部访问它。

class Dog {
  constructor() {
    this.sound = 'woof';
  }
  talk() {
    console.log(this.sound);
  }
}

let dog = new Dog();
console.log(dog.sound); // <--

// To further drive the point home, check out
// what happens when we change it
dog.sound = 'Meow?';
dog.talk();


完美!谢谢。 - Steez
@Steez 很高兴能帮到你 :) - Mike Cluck

0
你需要创建你的类的实例。

class Dog {
  constructor() {
    this.sound = 'woof';
  }
  talk() {
    console.log(this.sound);
  }
}

console.log(new Dog().sound);


0
你需要使用 new 创建类的实例。当你没有类的实例时,构造函数尚未执行,因此还没有声音属性。
var foo = new Dog();
console.log(foo.sound);

或者

这将为Dog类分配一个默认属性,而无需创建一个新实例。

Dog.__proto__.sound = 'woof';
console.log(Dog.sound);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接