簡體   English   中英

無法將回調函數用作對象方法

[英]Unable to use callback function as an object method

對象方法通常像這樣聲明和使用

points = { 
  first : function(){
    return this.val[0];
  }
};
points.val = [1,2];
points.first(); // returns 1

但是為什么我不允許使用回調代替聲明的方法。

points.val = [1,2];
points.(function(){
    return this.val[0];
  })();

在對象上調用方法包括兩個步驟:

  1. 通過鍵查找對象屬性
  2. 執行返回的屬性(必須是一個函數,或者TypeError )。

在第一個示例中,您的調用代碼使用. 語法,該方法first獲取具有鍵的points的屬性。 然后,它執行返回的屬性,這是一個匿名函數。

在第二個示例中,您嘗試使用鍵查找對象:

(function(){
  return this.val[0];
})

在JavaScript中, 對象鍵必須是有效的identifier 函數表達式不是有效的標識符,因此編譯器會引發SyntaxError

如果你想使用使用動態定義的函數thispoints ,你可以使用bind

(function() { return this.val[0] }).bind(points)()

您可以在需要回調的點上定義函數

var points = {val:[1,2]};
points.func = function(callback){
    callback.call(this);
}

並用

points.func(function(){
    return this.val;
})

不能將函數用作對象鍵,但是可以向對象添加函數。 您也可以定義一個函數之外的對象,並使用.call.apply方法

function val(){
    return this.val;
}

val.call(points);

我認為您正在嘗試做的是獲取/獲取積分。

points={};

// pass in an array to set points or pass a callback to retrieve them!
points.val = function (points){
//test if points is a callback return points to callback
if (typeof points==="function") return points(this._points); 
// or set the points with the passed in value
this._points=points;
};

//set the points
points.val([1,2])

//get points into callback

points.val(function(e){
    return e[0];
});

暫無
暫無

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

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