gpt4 book ai didi

javascript - js获取函数中调用对象的类

转载 作者:行者123 更新时间:2023-12-03 02:54:21 24 4
gpt4 key购买 nike

我有一个与此类似的结构:

 class Person {
greet() {
console.log(this.constructor.name)
}
}

class User extends Person {
}

let user = new User()
user.greet()

不幸的是,它为 this.constructor.name 打印 window 而不是 User。还有其他方法可以获取实际的类名吗?

实际代码:

static MeteorMethod(target: MeteorModel, key: string, descriptor: PropertyDescriptor) {
let constructor = target.constructor
let className = target.constructor.name
let methodName = key
let method = descriptor.value
let meteorMethodName = MeteorModelDecorators.generateMethodName(constructor, methodName)
MeteorModelDecorators.MeteorMethodClasses[className] = target

if(Meteor.isServer) {
Meteor.methods({
[meteorMethodName]: (modelClassName: string, modelProps: object, ...args: any[]) => {
let model = new MeteorModelDecorators.MeteorMethodClasses[modelClassName](modelProps)
method.apply(model, args)
}
})
}
else {
descriptor.value = async function(...args: any[]) {
// here I expect this to be Book, but I get Window
return new Promise(function(resolve, reject) {
Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
if(error) reject(error)
resolve(result)
})
})
}
}
}

class MeteorModel {
@MeteorMethod
save() {
console.log('save')
}
}

class Book extends MeteorModel {
}

let book = new Book()
book.save()

最佳答案

您的问题出在这部分:

descriptor.value = async function(...args: any[]) {
// here I expect this to be Book, but I get Window
return new Promise(function(resolve, reject) {
Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
if(error) reject(error)
resolve(result)
})
})
}

必须是这样的:

descriptor.value = async function(...args: any[]) {
// With the arrow function, should be Book
return new Promise((resolve, reject) => {
Meteor.call(meteorMethodName, this.constructor.name, this, args, (error: any, result: any) => {
if(error) reject(error)
resolve(result)
})
})
}

您传递给 Promise 构造函数的函数正在设置一个新的上下文,通过使用箭头函数,您可以从周围的方法中获取 this 上下文。

关于javascript - js获取函数中调用对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702344/

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