简体   繁体   English

访问没有`this`的对象方法

[英]Accessing object methods without `this`

Can I write something like the following without using this ? 我可以在不使用this情况下编写如下内容吗? I want map to return another object with the same method names and method foo changed. 我希望map返回另一个具有相同方法名称和方法foo的对象。 How can I access another method of an object without this? 如何在没有这个的情况下访问对象的另一个方法?

function createSomething() {
    const foo = () => 1
    function map(f) {
        const newFoo = () => f(this.foo())
        return {
            foo: newFoo,
            map: map
        }
    }
    return {
        foo: foo,
        map: map
    }
}

const s = createSomething()
            .map( x => x+1 )
            .map( x => x*x )
            .foo()  // s === 4

In your case its easy: 在你的情况下它很容易:

const newFoo = () => f(foo())

However, you could build a new instance at every mutation and pass a state through it ( that would make it a lot easier): 但是,您可以在每个突变处构建一个新实例并通过它传递一个状态(这会使它更容易):

function createSomething(state = 1){
  return {
    map(func){
      return createSomething(func(state));
    },
    forEach(func){
      func(state);
      return createSomething(state);
    },
    state(){ return state }
  };
}

So you can do: 所以你可以这样做:

 createSomething(5)
   .map( a => a +2)
   .forEach( console.log) //7
   .map( a => a + 8 )
   .forEach( console.log) //15
   .state() // 15

 const start = createSomething(5),
       second = start.map( a => a + 5),
       last = second.map(a => a + 5);

 console.log(
   start.state(),//5
   second.state(),//10
   last.state()//15
 );

Here's another way you can do it – you'll see this form expressed in lots of my other answers here on the site 这是你可以做到的另一种方式 - 你会在网站上看到我的其他答案中表达的这种形式

 const Box = value => ({ value: value, map: f => Box (f (value)), ap: ({value: other}) => Box (value (other)), inspect: () => `Box {${value}}` }) const square = x => x * x console.log (Box (3) .map (square)) // Box {3} console.log (Box (square) .ap (Box (4))) // Box {16} 

And another way you can do it without the infix-style interface. 另一种方法是你可以在没有中缀式界面的情况下完成它。 The inspect code here is a little kludgy, but the idea is you'd only leave that stuff attached to development code 这里的inspect代码有点笨拙,但想法是你只留下附加在开发代码上的东西

 const Box = { make: value => ({ type: Box, value, inspect: Box.inspector (value) }), map: (f, b) => Box.make (f (b.value)), ap: (x, f) => Box.make (f.value (x.value)), inspector: value => () => `Box {${value}}` } const square = x => x * x console.log (Box.map (square, Box.make (3))) // Box {3} console.log (Box.ap (Box.make (4), Box.make (square))) // Box {16} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM