如何始终使"this"关键字引用父类(将子方法绑定到父类)?



这里是我的问题的最简单形式:

class Service1 {
constructor() { this.name = 'service1' }
getThisName() { console.log('Name: ' + (this && this.name)) }
}
const service1 = new Service1();
service1.getThisName() // 'service1' => :)
function mapper(fn, ...params) {
this.name = 'mapper';
// ...params can be parsed or generated here
fn(...params);
}
mapper(service1.getThisName) // undefined => :'(

我知道我可以在mapper函数中使用fn.bind(service1)来解决问题,但由于fn是动态的,我不愿意这样做
我尝试过搜索如何从子方法中获取父类,但没有得到结果。

如果可能的话,我希望mapper能够调用类(或对象(的方法,而不会以可读直接的方式丢失此引用。CCD_ 5总是在同一上下文中被调用。

javascript中有办法解决这个问题吗


我尝试了什么

function mapper(fn, serviceClass) {
fn.bind(serviceClass)();
}
mapper(service1.getThisName, service1) // OK but is not readable and seems hacky
function mapper(serviceClass, fnName) {
serviceClass[fnName]();
}
mapper(service1, 'getThisName') // OK but autocompletion in the IDE don't work
function mapper(fn) {
fn();
}
mapper(service1.getThisName.bind(service1)) // the "best practice" but in my case not enougth readable

真实用例上下文

在实际的用例场景中,mapper被称为api2service。顾名思义,它与expressJs一起用于将api路由映射到服务。以下是代码的简化版本:

app.get(
'get/all/users', // api endpoint
api2service(
userService.getAll, // getAll take filter as the first param
['req.query'] // req.query is the filter and is mapped AND parsed as the first param of the service function. Eg: {name: 'blah'}
)
)

该代码重复了很多次,并且总是在同一上下文中调用,这就是为什么我需要一些可读的,而不是严格遵守良好实践。

在实现绑定运算符建议之前,您对此无能为力。除了尝试之外,您还可以在构建时自动绑定方法(另请参阅https://github.com/sindresorhus/auto-bind):

function autoBind(obj) {
let proto = Object.getPrototypeOf(obj);
for (let k of Object.getOwnPropertyNames(proto)) {
if (typeof proto[k] === 'function' && k !== 'constructor')
obj[k] = proto[k].bind(obj)
}
}
class Service1 {
constructor() {
this.name = 'service1'
autoBind(this);
}
getThisName() { console.log('Name: ' + (this && this.name)) }
}
function mapper(fn) {
fn();
}
let srv = new Service1
mapper(srv.getThisName)

或者使用绑定代理:

function Bound(obj) {
return new Proxy(obj, {
get(target, prop) {
let el = target[prop];
if(typeof el === 'function')
return el.bind(target)
}
})
}
class Service1 {
constructor() {
this.name = 'service1'
}
getThisName() { console.log('Name: ' + (this && this.name)) }
}
function mapper(fn) {
fn();
}
let srv = new Service1
mapper(Bound(srv).getThisName)

最新更新