4

我在这里读了一篇文章:

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了 object 而不是上面this也没有new使用关键字。它将如何应用于多个对象实例?它本质上与使用相同this吗?

4

2 回答 2

4

在您的示例中,that是由这一行创建的新对象:

var that = {};

然后该函数继续设置该对象的属性。

另一方面,this与构造函数一起使用——当使用 using 调用时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');
于 2012-02-21T05:45:57.370 回答
2

尚未指出的使用对象文字构造函数(您的代码)的一个优点是,当您创建对象的新实例时,new关键字不是必需的。或者换句话说,如果您只是忘记使用new关键字,您的代码仍将按预期运行,因为您不再依赖于使用new关键字this在构造函数中为新创建的对象提供范围;该that对象现在正在为您处理范围。

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

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

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

如果您要调用Car('Dodge Viper');or var MyCar = Car('Dodge Viper');this则函数中的 the 实际上将引用全局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);

于 2013-05-07T11:48:02.427 回答