2012-02-14 44 views
2

Javascript的问题。
关于模式或表达,可能是重复的问题。声明和获取js对象的最佳方式是什么? (图案)

您可以在下面使用其中的三个获取对象。 结果对象工作原理相同。

当您使用沉重的JavaScript web应用程序时,哪种模式最好?

为了,
1.对象文字的情况下
2.关闭情况下
3.新情况

function car = { 
    name: 'Q5', 
    type:'SUV', 
    wheels:4, 
    door:2, 
    score: 0, 

    getWheel: function(){return this.wheels;}, 
    getDoor: function(){return this.door;}, 
    setScore: function(score){ this.score = score;} 
} 




var car = (function(){ 
    var name = 'Q5', 
    type ='SUV', 
    wheels = 4, 
    door = 2, 
    score = 0; 

    return { 
    getWheel: function(){return wheels}, 
    getDoor: function(){return door}, 
    setScore: function(_score){ score = _score;} 
    } 
})(); 



var car = new function(){ 
    var name = 'Q5', 
    type ='SUV', 
    wheels = 4, 
    door = 2, 
    score = 0; 

    this.getWheel = function(){return wheels} 
    this.getDoor = function(){return door} 
    this.setScore = function(_score){ score = _score;}  
} 

回答

2

没有 “最好” 的方式anonymouse功能。 JavaScript中有一些OOP模式,你提到的是其中的一种(也是一种流行的模式)。它本质上是一个典型的(或伪古典)模式,用封闭来封装基于私有类的静态变量。

还有其他模式(例如Douglas Crockford推荐的功能模式)。

我个人推荐伪古典模式(尽管哪种模式最好是辩论的热点领域)。

如果你是用JavaScript实现面向对象编程,我强烈建议您考虑采用具有OOP内置的,如该Dojo ToolkitClosure Library JavaScript库。其他库(例如jQuery,MOOtools,Ext等)都有OOP模块和/或插件。

或者

虽然有在JavaScript中没有类,也有构造函数和原型。当你有几个相似的对象时(例如用户列表中的用户),这些概念就派上用场了。您的代码示例使用了这两个概念。使用像myclass这样的名字,很难说出你想要建模的东西。下面是一个用户构造函数的例子,以及它对原型的扩展:

var User = function (name) { 
    this.name = name; 
}; 

User.prototype.sayHello = function() { 
    return "Hello, my name is " + this.name; 
}; 
相关问题