我对 JavaScript 和 Java 继承时的 this
行为有所不同表示怀疑。
在java中:
class Animal {
public String name = "animal";
void hello() {
System.out.println("hello " + this.name);
}
}
class Dog extends Animal {
public String name = "dog";
}
public class Main {
public static void main(String...args) {
Dog dog = new Dog();
dog.hello(); // hello animal
}
}
上面的代码会输出hello Animal
,看来当我在子类Dog的实例中调用hello方法时,它会输出父类Animal中的name属性。
但在 Javascript 中却有所不同:
class Animal {
constructor() {
this.name = 'animal';
}
hello() {
console.log('hello ' + this.name);
}
}
class Dog extends Animal {
constructor() {
super();
this.name = 'dog';
}
}
const dog = new Dog();
dog.hello(); // hello dog
正如你所看到的,具有相同逻辑的代码输出不同的结果。在JavaScript代码中,hello方法输出hellodog
,它是子类实例的name属性。
我还尝试了Python和C++,结果是Python的行为像JavaScript,而C++的行为像Java。
是因为 JavaScript 和 Python 是动态语言吗?但具体细节是什么?为什么要这样设计?
我应该读哪本书来了解它?
非常感谢,请原谅我的英语不好......
最佳答案
关于javascript - 为什么 `this` 在 JavaScript 和 Java 中继承时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50553125/