簡體   English   中英

具有此/綁定的JS原型作用域

[英]JS Prototype scope with this/bind

我有以下代碼在JavaScript中創建對象。 它使用原型定義函數和構造函數。

function objectClass(){
    this.variables = new Array();
}

objectClass.prototype = 
{
    contructor: objectClass,

    setInfo: function(){
        $.ajax({
            url: "info.json",
            success: function(){
                //for each json element returned...
                this.variables.push(json[i]);
            }
        });
    }
    getInfo: function(){
        return this.variables;
    },
}

這是我正在嘗試做的類似示例。 我需要能夠在調用obj.getInfo()時返回變量數組。 它總是拋出一個錯誤。 我相信這是因為“ this”是指ajax成功函數的范圍。

關於如何獲取它以引用對象變量的任何想法?

沒錯, this值不會自動傳遞,因此不會設置為實例。 要強制執行此操作,可以使用$.ajax接受的context屬性:

$.ajax({
    context: this, // `this` is the instance here

這會將成功回調中的this值設置為您指定的值。

暫無
暫無

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

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