我最近一直在深入研究 JavaScript,偶然发现了一个问题。
对象的以下实现之间有什么区别:
var myFunction1 = (function myFunction1() {})();
var myFunction2 = {}
var myFunction3 = function myFunction3() {}
或者使用执行完全相同任务的三个实现的更长示例。
<script>
var myFunction1 = (function myFunction1() {
var _privateVar = 'Private var';
this.publicVar = 'Public var';
function init( newPrivate, newPublic) {
_privateVar = newPrivate;
this.publicVar = newPublic;
}
function getPrivateVar(){
return _privateVar;
}
function setPrivateVar(string){
_privateVar = string;
}
return {
init: init,
getPrivateVar: getPrivateVar,
setPrivateVar: setPrivateVar
}
})();
var myFunction2 = {
_privateVar: 'Private var',
publicVar: 'Public var',
init: function init( newPrivate, newPublic) {
this._privateVar = newPrivate;
this.publicVar = newPublic;
},
getPrivateVar: function getPrivateVar(){
return this._privateVar;
},
setPrivateVar: function setPrivateVar(string){
this._privateVar = string;
}
}
var myFunction3 = function myFunction3() {
var _privateVar = 'Private var';
this.publicVar = 'Public var';
function init( newPrivate, newPublic) {
_privateVar = newPrivate;
this.publicVar = newPublic;
}
function getPrivateVar(){
return _privateVar;
}
function setPrivateVar(string){
_privateVar = string;
}
return {
init: init,
getPrivateVar: getPrivateVar,
setPrivateVar: setPrivateVar
}
}
var a, b, c;
a = myFunction1;
a.init('Private var updated', 'Public var updated');
console.log('== A ==');
console.log(a.publicVar); // Public var updated
console.log(a._privateVar); // undefined
console.log(a.getPrivateVar()); // Private var updated
a.setPrivateVar('Private var is updated again');
console.log(a.getPrivateVar()); // Private var is updated again
b = myFunction2;
b.init('Private var updated', 'Public var updated');
console.log('== B ==');
console.log(b.publicVar); // Public var updated
console.log(b._privateVar); // Private var updated
console.log(b.getPrivateVar()); // Private var updated
b.setPrivateVar('Private var is updated again');
console.log(b.getPrivateVar()); // Private var is updated again
c = new myFunction3();
c.init('Private var updated', 'Public var updated');
console.log('== C ==');
console.log(c.publicVar); // Public var updated
console.log(c._privateVar); // undefined
console.log(c.getPrivateVar()); // Private var updated
c.setPrivateVar('Private var is updated again');
console.log(c.getPrivateVar()); // Private var is updated again
</script>
我知道前两个例子是单例,最后一个允许我创建多个对象。但是前两者有什么区别?或者它们是一样的,只是写的有点不同?