javascript - 在子类中调用 super() 后的属性查找实际上是如何工作的
问题描述
我有一个来自 MDN 的简单示例。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(this.name + ' barks.');
}
}
let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
现在,在子类中Dog
如何this.name
在引擎盖下工作。由于this
引用Dog
类实例并且名称不是存在于 Dog 实例上的东西。因此,要访问它,我们使用调用父构造函数的超级调用。我知道它看起来。
但是有人可以通过原型机制来解释(我很容易理解原型查找和链接机制)。
我确信在内心深处它会归结为这一点,但不清楚中间的步骤。谢谢!
解决方案
这是指 Dog 类
不,this
是指实例化的对象。实例化对象的内部原型为Dog.prototype
,Dog.prototype
内部原型为Animal.prototype
。
由于this
直接引用实例化对象(在构造函数和所有方法中),
this.name = name;
将name
属性直接放在该对象上,因此完全可以引用d.name
,或者在其中一个方法中this.name
:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(this.name + ' barks.');
}
}
const d = new Dog('Mitzie');
const dProto = Object.getPrototypeOf(d);
const secondProto = Object.getPrototypeOf(dProto);
console.log(dProto === Dog.prototype);
console.log(secondProto === Animal.prototype);
console.log(d.hasOwnProperty('name'));
推荐阅读
- c# - 基于调用实例交换重用实例的日志记录操作
- c# - 使用 Web API 和 SQL Server 查询的庞大数据集基于游标的分页
- excel - 为多个工作表添加循环代码工作
- java - @GuardedBy 是否保护某些东西?
- python-3.x - 如何修复 ImportError:无法从“Test”导入名称“testMethod”
- java - Intellige Idea java spring应用程序不启动调试
- windows - 文件系统过滤器驱动程序和文件系统微过滤器驱动程序有什么区别?(视窗)
- c# - XAML 解析异常 - 可以在应用程序的调试版本中找到附加属性,但在发布/安装版本中找不到
- r - 在 R 中使用 igraph 创建图形结构
- php - 有没有一种简单的方法可以在 Wordpress 帖子过滤器中添加“任何”选项?