[英]Can I return a function constructor and use in other function
Let's say I've something like this:-假设我有这样的事情:-
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 }
}
I can access people
data in other function
like normal (as shown below)我可以正常访问其他
function
中的people
数据(如下图)
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
}
But I can't seem to access Cars
and Bikes
function constructor
like the way I did with getting people data as show above.但我似乎无法访问
Cars
and Bikes
function constructor
,就像我在上面显示的获取人员数据的方式一样。 Currently I have something like this:-目前我有这样的事情: -
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)
}
It says allDataStuff is not a function
.它说
allDataStuff is not a function
。 What I want is to be able to access the Cars
and Bikes
function constructor from other function ( like show above ).我想要的是能够从其他 function访问
Cars
and Bikes
function 构造函数(如上图所示)。 Is it possible?可能吗?
You'll need to instantiate with new
keyword:您需要使用
new
关键字进行实例化:
let createNewPeopleData = () => {
let peopleData = allDataStuff()
let car = new peopleData.Cars(1,'Yamaha XYZ', 'Yamaha')
console.log(car)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.