gpt4 book ai didi

javascript - 有人可以解释这个 OOP javascript 结构吗

转载 作者:行者123 更新时间:2023-12-03 12:33:16 24 4
gpt4 key购买 nike

谁能解释一下这个 OOP javascript 结构?

我知道这是在 javascript 中创建“对象”的方式,只需要对符号及其含义做一些解释:

 var vote = function(){
return {
P1: function() {
alert('P1');
},

P2: function() {
alert('P2');
}

};

}();

vote.P1();
vote.P2();
  1. 为什么返回调用中有公共(public)方法?这怎么可能?用逗号分隔?

  2. 为什么'object'的结尾必须是(); ?

  3. 内部方法和公共(public)方法的命名约定?

  4. 公共(public)属性和方法是否具有相同的结构?有什么区别?

最佳答案

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();

私有(private)方法的命名约定通常是在方法/属性名称前加上下划线 _privateMethod: function(){}

关于javascript - 有人可以解释这个 OOP javascript 结构吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/546854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com