2017-09-09 7 views
1

Kann ich etwas wie das Folgende schreiben, ohne this zu verwenden? Ich möchte, dass map ein anderes Objekt mit den gleichen Methodennamen und Methoden foo zurückgibt. Wie kann ich auf eine andere Methode eines Objekts zugreifen?Zugriff auf Objektmethoden ohne `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 

Antwort

2

In Ihrem Fall ist es einfach:

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

Sie können jedoch eine neue Instanz bei jeder Mutation bauen und einen Zustand hindurchgehen (das wäre es viel einfacher machen):

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

So können Sie tun:

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 
); 
1

Hier ist eine andere Art und Weise Sie es tun können - Sie dieses Formular hier auf der Seite

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}
in vielen meiner anderen Antworten ausgedrückt sehen werden

Und eine andere Art und Weise Sie es ohne die infix- tun können Stil-Schnittstelle. Der inspect Code hier ist ein wenig kludgy, aber die Idee ist, würde man nur das Zeug zu Entwicklungscode

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}

angebracht leave
Verwandte Themen