javascript - 如何从类实例获取 JavaScript 类构造函数参数

标签 javascript typescript class oop ecmascript-6

我有一堆用不同数量的参数调用的类:

class Square {
    height;
    width;
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
}

这些类的实例存储在一个数组中以保持它们的时间轴:

const sq = new Square(22, 23);
const history = [sq];

我想找到一种从类构造函数中获取 arguments 的方法,据我所知:

history[0].contructor.arguments 

导致错误:

VM448:1 Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at :1:24

我想从构造函数中获取 arguments 关键字的内容(因此数组类对象同时具有高度和宽度参数)。

我意识到我可以使用父类(super class)并将它扩展到我需要此功能的所有类中,但理想情况下我想避免修改它们。有什么想法吗?

最佳答案

arguments 对象在其所属函数的局部范围内。在该函数之外无法访问它,除非您将它其他地方的函数传递。

如果您想知道哪些参数是从其他地方传递给构造函数的,那么您需要显式传递它们或让构造函数将它们存储在某个地方。

关于javascript - 如何从类实例获取 JavaScript 类构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58431038/

相关文章:

javascript - 获取与 jQuery 中的选择器匹配的下一个元素

java - 从泛型创建类对象

javascript - Jquery 选择 tbody 但不是从嵌套表中

javascript - 与多个页面上的 div 同步内容

javascript - 在页面中指定 ionic 组件 css 类

Angular2如何在另一个组件中使用一个组件的功能

C# 正确的程序结构

c++ - 错误 C2600 : what does this means?

javascript - 如何使用 AngularJS 将一个 .js 文件用于多个 .html 页面

javascript - 输入 radio 中的 ngModel?