2015-09-18 62 views
-1

我剛剛學過OOP,並且有一件事我無法解決。問題是某種範圍問題。如果構造函數在另一個函數內,新創建的對象調用構造函數undefined

如果我創建一個新對象,那麼如果構造函數在另一個函數內部,我將如何能夠訪問我的構造函數?現在我弄不明白。將函數存儲在全局變量中不會完成這項工作。

var example = new something x(parameter); 
    example.i(); 

    var getFunction; 

    var onResize = function() { 

     getFunction = function something(parameter) { 
      this.i= (function parameter() { 
        // Does something 
      }); 
     }; 
    }; 

window.addEventListener('resize', onResize); 
onResize(); 
+4

你偶然使用「構造函數」,「方法」,「父母」和「連接」這幾個字,甚至幾乎不可能開始猜測你的意思。另外,你的代碼在第一行有語法錯誤,第二行已經很奇怪了。請花點時間來更好地解釋你自己。 – jrsala

+0

@jrsala編輯我的帖子。這是否解釋得更好? – Asperger

+3

我明白你的意思,但你必須學會​​更好地表達自己,因爲你所說的話仍然是荒謬的。無論如何,在函數被定義之前,你不能'new'構造函數,所以你可以做的是等待它被定義,以便在'onResize'內部創建你的對象。並請修復代碼中的語法錯誤。 – jrsala

回答

0

對於OOP javascript,模式應該是這樣的。

//defining your 'class', class in quotes since everything is just functions, objects, primitives, and the special null values in JS 
var Foo = function (options) { 
    // code in here will be ran when you call 'new', think of this as the constructor. 

    //private function 
    var doSomething = function() { 
    } 

    //public function 
    this.doSomethingElse = function() { 
    } 
}; 

//actual instantiation of your object, the 'new' keyword runs the function and essentially returns 'this' within the function at the end 
var foo = new Foo(
    { 
     //options here 
    } 
) 
+0

它是否必須是從上到下?我實際上需要另一種方式。我知道有些圖書館設法以某種方式做到這一點。 – Asperger

+0

JavaScript變量總是被懸掛到範圍的頂部,但這並不意味着它們已被定義。在你想運行'new Foo()'時,必須定義Foo。編輯我不應該總是說,因爲不同的JS環境可能會有不同的表現 – teaflavored

+0

看到這個答案:http://stackoverflow.com/a/3344397/1830334 – gwg

0

如果我瞭解你,你想知道如何訪問另一個函數中的變量。您的嘗試是合理的,但請注意,getFunction未被綁定,直到onResize被調用。這是一個有點清潔演示:

var x; 

function y() { 

    // The value is not bound until y is called. 
    x = function(z) { 
     console.log(z); 
    } 
} 

y(); 
x('hello'); 

一種常見的JavaScript模式是返回代表函數的API的對象。例如:

function Y() { 
    var x = function(z) { 
     console.log(z); 
    } 

    return { 
     x: x 
    }; 
} 

var y = Y(); 
y.x('hello'); 

您應該明確瞭解JavaScript的基本概念。你的代碼和術語都是草率的。我建議Secrets of the JavaScript Ninja。它很好地解釋範圍和函數,這是JavaScript中兩個棘手的主題。

+0

我已經能夠構建插件,但似乎我混淆了術語,這大大降低了我與其他開發人員溝通的能力。我不知道爲什麼會發生這種情況。它以某種方式困擾我。也許是因爲我是OOP的新手。 – Asperger

+0

混合術語=>混淆概念。溝通是其中的一部分,但是要意識到這可能是一個更大的問題。 – gwg

+1

你是絕對正確的。你剛纔給我看的書真的很棒。我會在今天買這個 – Asperger

相關問題