gpt4 book ai didi

javascript - 嵌套对象中的“this”(JavaScript)

转载 作者:行者123 更新时间:2023-11-30 19:28:25 24 4
gpt4 key购买 nike

我想要一些像这样的对象结构(我知道那是不可能的)

const AUTH = {
base: 'auth',
login: {
enter: `${AUTH.base}/login`,
password: `${AUTH.base}/login/password`,
},
}

编辑:我还想将对象导出为模块

所以我做了一些体验

体验A

const AUTH_BASE = 'auth'
const AUTH_A = {
login: {
enter: `${AUTH_BASE}/login`,
password: `${AUTH_BASE}/login/password`,
}
}

console.log('enter ->', AUTH_A.login.enter)
console.log('recover ->', AUTH_A.login.password)

体验A输出:

enter -> auth/login
recover -> auth/login/password

体验 B

const AUTH_B = {
base: 'auth',
login() {
return `${this.base}/login`
},
password() {
return `${this.base}/login/password`
},
}

console.log('enter ->', AUTH_B.login())
console.log('recover ->', AUTH_B.password())

经验B输出:

enter -> auth/login
recover -> auth/login/password

经验C

const AUTH_C = {
base1: 'auth',
login: {
base2: 'auth????????????????',
enter1: function() {
return `${this.base1}/login`
},
enter2: function() {
return `${this.base2}/login`
},
password: function() {
return `${this.base}/login/password`
},
}
}

console.log('enter 1 ->', AUTH_C.login.enter1())
console.log('enter 2 ->', AUTH_C.login.enter2())
console.log('recover ->', AUTH_C.login.password())

体验C输出:

enter 1 -> undefined/login
enter 2 -> auth????????????????/login
recover -> undefined/login/password

体验D

const AUTH_D = {
base: 'auth',
login: {},
}

AUTH_D.login = {
enter: `${AUTH_D.base}/login`,
password: `${AUTH_D.base}/login/password`,
}

console.log('enter ->', AUTH_D.login.enter)
console.log('recover ->', AUTH_D.login.password)

经验D输出:

enter -> auth/login
recover -> auth/login/password

我的问题是:有没有更好的方法来实现我想要的语法?

repl.it 链接:https://repl.it/@SandroMiguel/Endpoints-constants-experience

最佳答案

你可以像这样使用静态类:

class Auth {
static base = 'auth'
static login = {
enter: `${Auth.base}/login`
}
}

或者使用 getter 来自引用对象

const AUTH = {
base: 'auth',
get login() {
return {
enter: `${AUTH.base}/login`,
password: `${AUTH.base}/login/password`
}
}
}

因此您可以像访问任何其他 props 一样访问您的属性:

console.log(AUTH.login.enter)
console.log(AUTH.login.password)

关于javascript - 嵌套对象中的“this”(JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56683893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com