簡體   English   中英

如何向對象添加函數並引用其成員?

[英]How can I add a function to an object and reference its members?

我有一堂課:

var MyClass = function(property, function){
    var me = this;

    me.property = property;
    me.function = function;
};

在另一個地方,我想添加一個引用類屬性的函數,如下所示:

var myClass = new MyClass({
    property: 5,
    function: function(){
        // do something with this.property
    }
});

this關鍵字不引用該對象。 有沒有一種方法可以進行設置,以便可以訪問通過傳入的匿名函數設置的屬性?

您應該將兩個參數作為兩個變量而不是作為對象傳遞,因為您的類不需要對象。

var myClass = new MyClass('some_property', function(){
    alert(this.property);
});

另外,請勿將function關鍵字用作argumemt, 請檢查此示例。 下面給出的代碼

var MyClass = function(prop, func){
    var me = this;
    me.prop = prop;
    me.func = func;
};

var myClass = new MyClass('some_property', function(){
    alert(this.prop);
});

myClass.func();

這里有幾個問題。

首先, function是JavaScript中的保留字,因此不能用作var名稱。 保留字: https//developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Reserved_Words

其次,您要傳遞對象文字而不是兩個預期參數。 因此,對於myClass var語句:

var myClass = new MyClass(5, function() { // do something with this.property });

我也建議不要將property用作變量名,因為它也有些混亂。

暫無
暫無

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

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