javascript - 你能/如何将构造函数添加到对象中吗?
问题描述
是否可以向对象添加构造函数?
如果以下是可能的,我想完成类似的事情:
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
但没有 a constructor
- 测试失败。
在childComponent
中init
被调用mount
:
init() {
const { position, map, title, icon } = this.props;
this.marker = new this.props.googleApi.Marker({
icon,
position,
map,
title
});
}
在酶测试中:
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 中,构造函数可以只是一个函数。看到这个。基本上这应该适合你:
beforeEach(() => {
props = {
googleApi: {
Marker: () => {}
},
map: {},
position: {
lat: 10,
lng: 10
},
title: "title",
icon: "icon"
};
});
推荐阅读
- django - 未提供身份验证凭据 django-rest-auth
- html - 格式化链接,以便它们在 CSS 中并排显示在网站的左上角
- java - 从 SQLite 数据库自动填充 Android Studio 中的 EditText
- angular - 如何在 Angular 5 中为 Angular 材料数据表创建可重用组件
- r - R:使用 tidyverse 的中值浓度时间序列图
- angular - matSort 无法正常工作
- android - 动画和可见性连接问题
- spring-data-jpa - Spring数据JPA OneToOne级联
- android - 当你更新你的应用程序时,服务会发生什么?
- python - 如何从 Pandas 系列中获取真/假面具?