![](/img/trans.png)
[英]Getting Function.prototype.bind.apply(…) is not a constructor error
[英]Passing arguments to object using Function.prototype.bind.apply(Obj, args) only passing first element
我有一个包装器类(单例),如下所示:
'use strict'
var _ = require('lodash')
var SDK = {
isInitialized: false,
isSharedInstance: true,
initSharedInstance: function() {
var args = Array.prototype.slice.call(arguments)
var self = this
if (self.isInitialized) {
console.log('SDK shared instance is already initialized')
return self
}
var SDKClient = require('./lib/client')
console.log('parent', args)
var client = Function.prototype.bind.apply(SDKClient, args)
_.assign(self, client)
Object.setPrototypeOf(self, new client())
self.isInitialized = true
self.isSharedInstance = true
self.SDKQuery = require('./lib/query')
}
}
SDK.init = SDK.initSharedInstance
module.exports = SDK
到SDK客户端类:
'use strict'
var _ = require('lodash')
var defaultOptions = {
baseUrl: 'url'
}
var UsergridClient = function() {
var self = this
self.isSharedInstance = false
var args = Array.prototype.slice.call(arguments)
console.log('child', args)
var options = _.isPlainObject(args[0]) ? args[0] : {}
if (args.length === 2) {
self.orgId = args[0]
self.containerId = args[1]
}
_.defaults(self, options, helpers.config, defaultOptions)
return self
}
使用此建议 ,看来我应该能够做到:
var client = Function.prototype.bind.apply(SDKClient, args)
_.assign(self, client)
Object.setPrototypeOf(self, new client())
但是由于某种原因,当我注销时,您会看到:
SDK.init('org', 'container')
// parent [ 'org', 'container' ]
// child [ 'container' ]
仍然很奇怪的是,当我仅传递一个参数时, child
退出为空数组。
该解决方案有什么问题? 如何正确地将完整的args数组传递给SDK客户端的单例初始化? 我的猜测是在bind.apply()
调用中缺少一些(或额外的)参数,但我不知道是什么。
您链接的帖子说
new Something(a, b, c)
相当于
new (Function.prototype.bind.apply(Something, [null, a, b, c]))
注意null
! 您仍然需要将函数绑定到某些东西上 -当将函数与new
使用时, 某些东西随后将被忽略,但是仍然需要传递一些东西。
你应该用
var args = [null];
args.push.apply(args, arguments);
apply()用于在数组[]中传递args。 因此,要使用apply()传递参数,您需要将其放入数组中。
apply(context,[arg1,arg2,...]
您可以使用call()-它正在做您想做的事情。
call(context, arg1, arg2,...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.