问题描述
学习类、原型等,这一切终于对我来说就位(至少可以说是非常令人兴奋的 :))) 但是,我的问题与找到类的对象原型有关,理论上我应该在那里找到它的方法。
例如:
class Color {
constructor(r,g,b,name) {
this.r = r;
this.g = g;
this.b = b;
this.name = name;
}
innerRGB() {
const { r,b } = this;
return `${r},${g},${b}`;
}
rgb() {
return `rgb(${this.innerRGB()})`;
}
rgba(a = 1.0) {
return `rgba(${this.innerRGB()},${a})`;
}
}
const red = new Color(255,67,89,"tomato");
innerRGB()、rgb() 和 rgba() 存储在哪里?我在 window 对象上找不到它们。他们在哪? Color 类存储在哪里?
当我在控制台中输入 Color() 时,我得到:
Uncaught TypeError: Class constructor Color cannot be invoked without 'new'
我很清楚构造函数的内部工作原理,但我不清楚原型所在的位置以及如何访问和检查它。
解决方法
以下是您的代码片段的对象关系:
中间的对象,red.__proto__
,又名 red.constructor.prototype
,又名 Object.getPrototypeOf(red)
,又名 Color.prototype
是存储方法的地方。
类 Color
本身(在图中为 ƒ Color
)的范围是它的包含块,就像任何其他变量一样。在 Javascript 中,类是函数,函数是变量:
{
// block started
class Color { // it's the same as "let Color = function...
...
}
// block ended
}
// "Color" doesn't exist here
,
如果您想访问实例的原型,请使用 __proto__
字段。如果您想查看类本身的原型,请使用 prototype
字段。
当您创建实例时,实例的 __proto__
字段设置为类的 prototype
字段时会发生什么。
instance.__proto__ === Class.prototype