javascript - 我可以返回一个函数构造函数并在其他函数中使用吗
问题描述
假设我有这样的事情:-
let allDataStuff = () => {
// declare data info
let people = {
name: "",
cars: [],
bikes: []
}
// cars data - function contructor
let Cars = function(id, name, brand) {
this.id = id
this.name = name
this.brand = brand
}
// bikes data - function contructor
let Bikes = function(id, name, brand, noOfWheels) {
this.id = id
this.name = name
this.brand = brand
this.noOfWheels = noOfWheels
}
// return all
return { people, Cars, Bikes }
}
我可以正常访问其他people
数据(如下所示) function
let createNewPeopleData = () => { // other function
// get people data info
let peopleData = allDataStuff().people
console.log(peopleData) // this will log out all data currently store in the object
}
但我似乎无法访问Cars
和Bikes
function constructor
喜欢我在获取人员数据时所做的方式,如上所示。目前我有这样的事情: -
let createNewPeopleData = () => { // other function
// let's just say I've values in all these vars define below
// create new car data
let newCar = allDataStuff().Cars(id, carName, carBrand) // this throw error
// push it into array of cars
allDataStuff().people[cars].push(newCar)
// create new bike data
let newBike = allDataStuff().Bikes(id, bikeName, bikeBrand, noOfWjeels) this throw error
// push it into array of cars
allDataStuff().people[bikes].push(newBike)
}
它说allDataStuff is not a function
。我想要的是能够从其他函数Cars
访问andBikes
函数构造函数(如上图所示)。是否可以?
解决方案
您需要使用new
关键字进行实例化:
let createNewPeopleData = () => {
let peopleData = allDataStuff()
let car = new peopleData.Cars(1,'Yamaha XYZ', 'Yamaha')
console.log(car)
}
推荐阅读
- react-router - 如何传递道具
到一个组件 - php - jQuery PHP Ajax基于进程保存多个选中框
- json - AWS API Gateway 映射模板 JSON
- python-3.x - 使用 ORM 加密 PostgreSQL 中的数据
- python - 在我的语言环境机器中设置一个现有的 django docker 项目
- codeigniter - Nginx 重写总是重定向
- c# - Interlocked.Increment 方法
- java - 从 jasper 报告中的哈希映射内的对象映射中获取值
- javascript - 使用 Cookie 的条件下拉重定向
- android - Firebase AuthUI 未显示登录流程