簡體   English   中英

僅通過第一個元素使用Function.prototype.bind.apply(Obj,args)將參數傳遞給對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM