为什么这个 JavaScript 类中的声音属性没有被正确地设置为私有?此外,如何在类外访问它?我在视频中看到过并尝试在类外访问声音属性,但失败了。
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
谢谢!!
为什么这个 JavaScript 类中的声音属性没有被正确地设置为私有?此外,如何在类外访问它?我在视频中看到过并尝试在类外访问声音属性,但失败了。
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
谢谢!!
这不是私有的,因为在创建类实例后可以从外部访问它。
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();
class Dog {
constructor() {
this.sound = 'woof';
}
talk() {
console.log(this.sound);
}
}
console.log(new Dog().sound);
new
创建类的实例。当你没有类的实例时,构造函数尚未执行,因此还没有声音属性。var foo = new Dog();
console.log(foo.sound);
或者
这将为Dog类分配一个默认属性,而无需创建一个新实例。
Dog.__proto__.sound = 'woof';
console.log(Dog.sound);