Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将参数传递给从另一个类调用方法的一个类上的便利方法_Javascript_Node.js - Fatal编程技术网

Javascript 将参数传递给从另一个类调用方法的一个类上的便利方法

Javascript 将参数传递给从另一个类调用方法的一个类上的便利方法,javascript,node.js,Javascript,Node.js,我有一个这样的原型方法: ProjectClient.prototype = { connect: function() { console.log('ARGS: ' + Array.prototype.slice.call(arguments) // this bit takes a data object, a relationship string, and another data object as arguments, //

我有一个这样的原型方法:

ProjectClient.prototype = {
    connect: function() {
        console.log('ARGS: ' + Array.prototype.slice.call(arguments)
        // this bit takes a data object, a relationship string, and another data object as arguments, 
        // e.g. client.connect(user1, 'likes', user2):
        var options = helpers.build.connection(this, Array.prototype.slice.call(arguments))
        request({
            uri: options.uri,
            method: 'POST',
            json: true
        }, function(error, response) {
            var customResponse = new CustomResponse(response)
            options.callback(error, customResponse)
        })
    }
}
这依赖于将
ProjectClient
的实例传递给
helpers.build.connection
方法。我还有一个正在使用的
ProjectClient
的“单例”共享实例。为方便起见,我将此
connect()
方法的副本添加到
ProjectEntity
中,如下所示:

ProjectEntity.prototype = {
    connect: function() {
        var args = Array.prototype.slice.call(arguments)
        args.unshift(this)
        return Project.connect(args)
    }
}
但是它工作不正常--在执行
console.log('ARGS:'+array.prototype.slice.call(arguments)
时,这会给我一个嵌套的参数数组:

我希望:

 ARGS: [ arg1, arg2, arg3 ]

有什么更一致的方法将参数传递给
ProjectClient.prototype.connect()
,这样我就可以得到我想要的?我也尝试过使用
Project.connect.apply(args)
,但是因为我返回函数(实际上不是在这里调用它)
Array.prototype.slice.call(参数)
以空数组结束。如果没有更好的方法,那么最好的解决方法是什么?

您可能希望像这样使用
.apply()
将任意参数集传递给函数:

ProjectEntity.prototype = {
    connect: function() {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(this);
        return Project.connect.apply(Project, args);
    }
}
.apply()
本身有两个参数。第一个参数是希望
参数位于正在调用的函数中的任何参数。第二个参数是希望作为单个参数传递给函数的参数数组(而不是作为数组本身传递)


更多关于
.apply()

Doh!当我尝试使用
apply
时,我缺少
Project
作为第一个参数。谢谢!@remus-如果这回答了你的问题,那么请通过标记一个接受的答案来完成。哦,奇怪……我在移动应用程序中接受了它。可能是搞错了。
ProjectEntity.prototype = {
    connect: function() {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(this);
        return Project.connect.apply(Project, args);
    }
}