[英]Can someone explain this OOP javascript structure
有人可以解釋這個OOP javascript結構嗎?
我意識到你是如何在javascript中創建“對象”的,只需要對符號及其含義進行一些解釋:
var vote = function(){
return {
P1: function() {
alert('P1');
},
P2: function() {
alert('P2');
}
};
}();
vote.P1();
vote.P2();
為什么返回呼叫中的公共方法? 這怎么可能? 被逗號隔開?
為什么'對象'的結尾必須是(); ?
內部方法和公共方法的命名約定?
公共屬性和方法結構是否相同? 有什么區別?
var vote = function(){
var privateMember = 3; // lets define a private member, this will only be available inside the function scope, so we can't do "vote.privateMember" because we're not returning it below
// It's returning an object, {}
// these are considered public because they are returned by the function, making them available outside the function scope using the "dot" operator, "vote.P1()"
return {
// first value of the object is a function
// so we can call this like "vote.P1()"
// we're calling a privateMember in here
P1: function() {
alert('P1');
alert(privateMember);
},
// second value of the object is a function
// so we can call this like "vote.P2()"
P2: function() {
alert('P2');
}
};
}(); // () means it will execute the function, so "vote" will store the return value of this function, it's a shorthand for `var vote = function(){}; vote = vote();
私有方法的命名約定通常是在方法/屬性名稱_privateMethod: function(){}
之前加下下划線。
它正在返回對象/哈希。 請注意,返回之后是{這是對象/哈希的開頭。
運行返回對象的匿名函數。
我不知道你的意思。
是的他們是一樣的。 屬性可以是函數,因為javascript具有一等函數。
這段代碼是設計的,所以很難說它有用。 我不確定作者的意圖是什么。 看起來他可能一直致力於創建一個類似於類的東西,而不是javascript基於原型OO的方式。 這段代碼可以很容易編寫。
var vote = {
P1: function() {
alert('P1');
},
P2: function() {
alert('P2');
}
};
三個重要概念:匿名函數,對象文字,閉包。
您可以聲明並執行函數,而無需將其賦值給變量。 在你的例子中,foo不是一個函數,它是調用的結果:
var item = function(){ /*function code here*/ }**()**;
< - 因為正在執行該函數,item是函數返回的對象,而不是函數。
假設你這樣做: var a = new Object(); a.foo = 'bar';
var a = new Object(); a.foo = 'bar';
對象文字符號如下所示: var a = {foo: 'bar'};
在您的示例中,您的匿名函數返回一個具有兩個函數P1和P2的新對象。 它只是指定對象的另一種表示法。
當函數返回一個對象時,該對象保留對函數作用域的訪問 - 這稱為閉包。 所以,如果你這樣做:
var a = function(){
var _pvt = 'foo';
return {
aFunc: function(){alert(_pvt);}
};
}();
a.aFunc();
_pvt
的范圍是匿名函數。 此函數使用一個方法( aFunc
)返回一個新對象。 匿名函數的作用域通過閉包可用於此對象,因此當a.aFunc()
時, _pvt
將可用。
最有趣的地方是YUI Theatre上的Douglas Crockford視頻: http : //video.yahoo.com/watch/111585/1027823
這是JSON(javascript對象表示法)。 它類似於python中的字典格式。
可以使用內聯定義數組
[1,2,3,4,5]
和對象可以使用內聯定義
{ field1: value1, field2: value2, field3: value3 }
一個函數也可以內聯定義,
var a = function() { .... } //a is a function
函數后面的()用於在定義后立即調用函數! 因為函數是內聯定義的,所以就像說:
x = function() { ... }
y = x();
但濃縮為:
y = function(){...} ();
據我所知,沒有公共或私有,它都是公開的,函數與變量沒有區別,只是它們的類型是一個函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.