gpt4 book ai didi

javascript - 您可以/如何将构造函数添加到对象中?

转载 作者:行者123 更新时间:2023-11-30 14:11:31 25 4
gpt4 key购买 nike

是否可以向对象添加构造函数?

如果以下是可能的,我想完成类似的事情:

const constructorObject = {
Constructor: Constructor("content")
}

如果访问了该对象,您将能够执行以下操作:

new constructorObject.constructor({ content: "content" }):

没有收到错误提示:

undefined is not a constructor 
(evaluating 'new constructorObject.Constructor({ content: "content })')

对于上下文,我有一个 react 组件,我正在调用 parent 组件中的 googleAPI。

this.googleAPI 被传递给 child。当我运行测试时 - props 被传递给 child 但对象中没有 constructor - 测试失败。

childComponent 中,initmount 上被调用:

init() {
const { position, map, title, icon } = this.props;
this.marker = new this.props.googleApi.Marker({
icon,
position,
map,
title
});
}

在 enzyme 测试中:

import React from "react";
import { shallow } from "enzyme";
import Child from "src/components/child";

describe("components/child", () => {
let props;
beforeEach(() => {
props = {
googleApi: {},
map: {},
position: {
lat: 10,
lng: 10
},
title: "title",
icon: "icon"
};
});

describe("on mount", () => {
it("should render into the document", () => {
const component = shallow(<Marker {...props} />);
expect(component).to.not.be.null;
});
});
});

这是 enzyme 错误:

undefined is not a constructor (evaluating 'new this.props.googleApi.Marker({ title: this.props.title })')

最佳答案

在 JS 中,构造函数可以只是一个函数。参见 this .基本上这应该适合你:

beforeEach(() => {
props = {
googleApi: {
Marker: () => {}
},
map: {},
position: {
lat: 10,
lng: 10
},
title: "title",
icon: "icon"
};
});

关于javascript - 您可以/如何将构造函数添加到对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54357455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com