猿问

可以在 JS 中同时充当对象和函数吗?

我正在尝试为我的 api 创建一个编程接口,我有以下路线


'api/location/:locationId/users' get, post

'api/location/:locationId/users/:userId' get, post, put

我想像这样使用它


var myApi = new API('baseUrl');

myApi.api.location(locationId).users.get()

myApi.api.location(locationId).users.post(data)

myApi.api.location(locationId).users(userID).get()

myApi.api.location(locationId).users(userID).post(data)

myApi.api.location(locationId).users(userID).put(data)

所以我开始写这门课并意识到这不是直截了当的


class API{

  constructor(baseUrl) {

    this.axios = axios.create({ baseURL });;

  }

  this.api = {

     location: (locationId) => {

        users: ...(stuck)

     }

  }

}

我知道有不同的方法可以做到这一点,但我想知道是否“可能”在 javascript 中同时充当函数和对象


IE。


var a = ..?..

a(blah) // returns an output

a.get(blah) // returns an output


慕妹3242003
浏览 147回答 2
2回答

慕标琳琳

这当然是可能的:var myObj = {  someFunc: () => "foo"}myObj.someFunc.bar = "baz";console.log(myObj.someFunc());console.log(myObj.someFunc.bar);函数就像 JavaScript 中的几乎所有其他东西一样是对象。这意味着您可以向它们添加属性。

qq_笑_17

知道了。class API {  constructor(baseUrl) {    this.baseUrl = baseUrl;    this.api = {       location: (locationId) => ({          users: (() => {            var a = (userId) => ({              get: () => `${this.baseUrl}/api/location/${locationId}/users/${userId}`            })            a.get = () => `${this.baseUrl}/api/location/${locationId}/users`;            return a          })()       })    }  }}var myApi = new API('baseUrl');myApi.api.location('locationId').users.get()// "baseUrl/api/location/locationId/users"myApi.api.location('locationId').users('userId').get()// "baseUrl/api/location/locationId/users/userId"
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答