首页 > 解决方案 > 你能/如何将构造函数添加到对象中吗?

问题描述

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

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

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- 测试失败。

childComponentinit被调用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 })')

标签: javascriptreactjsconstructorenzyme

解决方案


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

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

推荐阅读