簡體   English   中英

是否可以將參數傳遞給設置為對象文字值的函數?

[英]Can a parameter be passed to a function that is set as an object literal value?

我有一個函數functionWithDifferentScope ,該函數將對象myobject.options作為參數。 options對象中的一對對象是回調,它指向myObject中定義的函數: myCallback

我要實現的目標是將myObject 命名空間注入到在全局級別(由第3方定義)的函數的回調中。

一個簡化的例子:

var myObject = {
    options: {
        callback: this.myCallback(this),
        ...,
    },

    init: function() {
        // functionWithDifferentScope operates in the 'window' context
        functionWithDifferentScope(this.options);
    },

    myCallback: function(namespace) {
        // 'this' is window
        // 'namespace' is myObject
    }
}

myObject.init();

執行此腳本時, this.myCallback(this)似乎在定義時執行(由於括號?); 以及一次myObject.init(); 被校准。 在第一次處決myObject的 ,而是通過functionWithDifferentScope后續調用標識窗口

有沒有辦法將myObject 命名空間作為參數傳遞給myObject.options.callback值?

我認為您正在尋找的是原型樣式“綁定”

基本上,“ this.myCallback(this)”是對該函數的調用。

this.myCallback是函數本身。 (它是帶有類型函數的對象)。

您可以使用可以在函數上使用的方法“ call”或“ apply”來調用它。 將調用這些函數。

看到:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply?redirectlocale=zh-CN&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fapply

第一個參數是要使用的對象上下文。我認為您所說的對象名稱空間是什么。

因此: a.callback(5)a.callback.call(a,5)

但是請注意,這些天,如果您使用的是大多數javascript庫,則可能有一個“綁定”功能可以為您完成工作。

http://prototypejs.org/doc/latest/language/Function/prototype/bind/

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

這個想法是this.callback.bind(this)返回一個您可以調用的Function對象,該對象將自動注入正確的上下文,因此您可以單獨將bind的返回值作為回調傳遞,並確保該方法將在正確的對象。

你是這個意思嗎

var myObject = new (function() {
    var t = this;

    vac callback = function() {
        // t equals to the myObject-instance
        // this equals to window
    }

    this.init = function() {
        funcWithDifferencScope(callback);
    }
})();

myObject.init();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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