我已經閱讀了很多關於封閉和原型的文章......但我仍然有一些問題。 http://blogs.msdn.com/b/kristoffer/archive/2007/02/13/javascript-prototype-versus-closure-execution-speed.aspxJavascript - closure - syntax - public members
我的問題是關於揭露公共方法: 我從這篇文章開始
這是方法:
從這個// Closure implementation
function Pixel(x, y){
this.x = x;
this.y = y;
this.getX = function(){
return this.x;
}
this.getY = function(){
return this.y;
}
this.setX = function(value){
this.x = value;
}
this.setY = function(value){
this.y = value;
}
}
不同:
// Closure implementation
function Pixel(x, y){
this.x = x;
this.y = y;
return {
getX : function(){
return this.x;
},
getY : function(){
return this.y;
},
setX : function(value){
this.x = value;
},
setY : function(value){
this.y = value;
}
}
}
哪一個是最好的嗎?爲什麼?
最後一個問題:從上面的基準中,有沒有一種方法可以使用閉包來獲得與原型相似的性能?
tx
這些示例並不等同,也沒有真正使用閉包。拿第二個例子並運行'(new Pixel(4,2))。getX()'。返回值將是'undefined'而不是'4'。假設你解決了這個問題,最大的區別在於,在第二種情況下,實例化(返回)的對象不會從'Pixel.prototype'繼承,像'obj instanceof Pixel'這樣的測試會失敗。 –
第一個示例是「類」定義,第二個示例完全不起作用。這是不同的。 – jbabey