2012-02-21 82 views
4

我在这里读了一篇文章:JavaScript对象创造模式

http://javascriptweblog.wordpress.com/2010/03/16/five-ways-to-create-objects/

它讲述了约五创建对象的方式。但我的问题是他的方式一(3):

myApp.Notepad = function(defaultFont) { 
    var that = {}; 
    that.writeable = true; 
    that.font = defaultFont; 
    that.setFont = function(theFont) { 
     that.font = theFont; 
    } 
    return that; 
} 

myApp.notepad1 = myApp.Notepad('helvetica'); 

按作者,我们可以使用它时,多个实例需要,我们可以使用从3(以上)的任何图案以5

但据我所知,我们确实需要使用this关键字,它反映了新创建的实例,并且仅指那个实例。但是,以上,作者使用that对象而不是this,并且上面没有使用new关键字。它将如何应用于多个对象实例?它是否与使用this相同?

回答

4

在您的例子,that是通过这条线创建新对象:

var that = {}; 

该函数然后前进到设置该对象的属性。

在另一方面,this使用具有构造函数 - 使用new调用时,将自动创建一个新对象,并传递给函数作为this。同样的例子可以写成:

的使用对象字面构造器(代码)的
myApp.Notepad = function(defaultFont) { 
    this.writeable = true; 
    this.font = defaultFont; 
    this.setFont = function(theFont) { 
     this.font = theFont; 
    } 
} 

myApp.notepad1 = new myApp.Notepad('helvetica'); 
+0

感谢,但我知道什么是优势,使用'that'对象,而不是使用'this'构造方法的? – Dev555 2012-02-21 05:49:36

+1

@ Dev555 - 这只是一种不同的(围绕)“构建”对象的方式。我不知道它是否有优势,但微妙之处在于'setFont'函数使用闭包,而不是引用'this'对象。 'setFont'使用在其外部定义的那个''''。从语法上讲,它稍微不清楚它在做什么,因为它会对'new'运算符进行旁路操作。 – Seth 2012-02-21 06:05:00

+0

@Seth:这就是混乱,等待事情得到澄清。谢谢 – Dev555 2012-02-21 06:10:35

2

一个优势还没有被指出,但是,当你创建了一个对象的新实例,该new关键字不是必需的。或者换句话说,如果你只是忘记使用new关键字,您的代码将仍然运行如预期,你不再是依赖于使用的new关键字中以得到this范围,新创建的对象的构造函数; that对象现在正在考虑你的范围。

这是YUI库(和Douglas Crockford)为构造函数所采用的方法。

考虑以下的简单构造函数:

var Car = function(model){ 
    this.model = model; 
}; 

如果你打电话给Car('Dodge Viper');甚至var MyCar = Car('Dodge Viper');,则this在功能实际上指的是全球window对象。所以现在上面的属性Model实际上是一个全局变量,这可能不是预期的。

var Car = function(model) { 
 
    var that = {}; 
 
    that.model = model; 
 
    return that; 
 
}; 
 

 
// Both work the same. 
 
var MamsCar = new Car("Mini Cooper"); // with 'new' 
 
var DadsCar = Car("Bugatti Veyron"); // without 'new' 
 
alert("Mam's car is a " + MamsCar.model + " and dad's car is a " + DadsCar.model);