从对象内部的函数中访问此函数而没有回调?

时间:2019-01-05 23:20:27

标签: javascript

我试图从子对象中调用对象(在本例中为o)。

如示例中所示:wrap.instances内部有10个o实例,并且我想通过wrap从DOM调用中调用这些实例之一。当我调用var t(将此变量设置为a())时,如何将范围设置为o而不是其功能?

谢谢!

//DOM call
$('#app').on('click', '[call]', function(e) {
    wrap.call($(this).attr('call'));
});

//Wrap
const wrap = {
    instances: {},
    call: function(k) {
        this.instances[k].fn.a();
    }
}

//Instance o
let o = {
    fn: {
        a: function() {
            var t = this; //This is a, not o
            t.fn.b(); //Error, since scope is function a
        },
        b: function() { }
    }
};

3 个答案:

答案 0 :(得分:2)

尝试:

this.instances[k].fn.a.apply(this.instances[k]);

答案 1 :(得分:0)

您可以将package com.example; import java.net.Socket; import javax.net.SocketFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.annotation.Transformer; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter; import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory; import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory; import org.springframework.integration.transformer.ObjectToStringTransformer; import org.springframework.messaging.MessageChannel; @SpringBootApplication public class So39290834Application { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(So39290834Application.class, args); Socket socket = SocketFactory.getDefault().createSocket("localhost", 9999); socket.getOutputStream().write("foo\r\n".getBytes()); socket.close(); Thread.sleep(1000); context.close(); } @Bean public TcpNetServerConnectionFactory cf() { return new TcpNetServerConnectionFactory(9999); } @Bean public TcpReceivingChannelAdapter inbound(AbstractServerConnectionFactory cf) { TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(cf); adapter.setOutputChannel(tcpIn()); return adapter; } @Bean public MessageChannel tcpIn() { return new DirectChannel(); } @Transformer(inputChannel = "tcpIn", outputChannel = "serviceChannel") @Bean public ObjectToStringTransformer transformer() { return new ObjectToStringTransformer(); } @ServiceActivator(inputChannel = "serviceChannel") public void service(String in) { System.out.println(in); } } 的功能.bind

o

答案 2 :(得分:0)

因为您的调用上下文是fn,所以另一种选择是将a函数更改为调用this.b(以便引用fn.b)而不是{{ 1}}(这需要this.fn.b的非标准调用上下文):

o