有人可以解释这个OOP javascript结构吗?
我意识到你是如何在javascript中创建"对象"的,只需要对符号及其含义进行一些解释:
var vote = function(){
return {
P1: function() {
alert('P1');
},
P2: function() {
alert('P2');
}
};
}();
vote.P1();
vote.P2();
Run Code Online (Sandbox Code Playgroud)
为什么返回呼叫中的公共方法?这怎么可能?被逗号隔开?
为什么'对象'的结尾必须是(); ?
内部方法和公共方法的命名约定?
公共属性和方法结构是否相同?有什么不同?
Luc*_*eis 12
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();
Run Code Online (Sandbox Code Playgroud)
私有方法的命名约定通常是在方法/属性名称之前加下一个下划线_privateMethod: function(){}
.
归档时间: |
|
查看次数: |
1027 次 |
最近记录: |