我最近一直在深入研究JavaScript,並偶然發現了一個問題。3種不同類型的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>
我知道這兩個第一個例子是單例,最後一個例子允許我創建多個對象。但前兩者有什麼區別?或者它們是相同的,只是寫了一點點不同?
在你的第一個例子'var myFunction1 =(function myFunction1(){})();'不給你一個對象。它將函數的返回值存儲到myFunction1中。 – nderscore
@nderscore是的,但不是myFunction2在做同樣的事情嗎? – jamietelin
不; myFunction2不是一個函數。 – SLaks