首页 > 解决方案 > 我可以返回一个函数构造函数并在其他函数中使用吗

问题描述

假设我有这样的事情:-

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
}

但我似乎无法访问CarsBikes 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函数构造函数(如上图所示)。是否可以?

标签: javascriptfunctionconstructorreturnself-invoking-function

解决方案


您需要使用new关键字进行实例化:

let createNewPeopleData = () => {
    let peopleData = allDataStuff()
    let car = new peopleData.Cars(1,'Yamaha XYZ', 'Yamaha')
    console.log(car)
}

推荐阅读