2011-05-08 15 views
2

我想开始适当地组织我的代码,所以我想使用对象文字。在下面的例子中,我正在做一个伪类。我希望init()可以作为构造函数工作,但不幸的是,我没有看到如何根据对象上下文来设置属性。Javascript对象文字,如何解决上下文?

var car = { 
    context : this, 
    wheels : 0, 
    color : '', 
    speed : 0, 
    init : (function(x){ 
     console.log(x); 
     x.wheels = 4; 
     x.color = 'red'; 
     x.speed = 120; 
    })(context) 
}; 

console.log(car.color); 
+0

你究竟想要达到什么目的? 和它有何不同:'var car = new Car();' – 2011-05-08 21:00:13

+0

一个Object对象没有this属性,只有Function对象。在一个函数中,'this'是一个属于激活对象(实际上是一个变量)的关键字,它不是一个公共属性。最后,函数的'this'由调用设置,不能静态设置(尽管可以使用ES5和* bind *)。 – RobG 2011-05-08 23:16:01

回答

5

在声明对象文字时,您不能立即运行这样的函数。你可以做什么:

var car = { 
init : function(wheels,color,speed){ 
    this.wheels = wheels || 0; 
    this.color = color || ''; 
    this.speed = speed || 0; 
    return this; 
    } 
}.init(4,'red',120); 

alert(car.speed); //=>120 

这消除需要:

context : this, 
wheels : 0, 
color : '', 
speed : 0, 

...并提供了可能性:

var car = { 
    init : function(wheels,color,speed){ 
     this.wheels = wheels || 0; 
     this.color = color || ''; 
     this.speed = speed || 0; 
     return this; 
    } 
    }, 
    redAndFast = car.init(4,'red',230), 
    threeWheeler = car.init(3,'yellowstriped',110); 

[编辑]什么was我在想什么?如果你想要租车的更多情况下,你必须使用真实constructor函数,而不是一个对象字面的:

var Car = function(){ 
    return { 
    init : function(wheels,color,speed){ 
      this.wheels = wheels || 0; 
      this.color = color || ''; 
      this.speed = speed || 0; 
      return this; 
    } 
} 
}, 
redAndFast = new Car().init(4,'red',230), 
threeWheeler = new Car().init(3,'yellowstriped',110); 

这可以简化为:

var Car = function(wheels,color,speed){ 
      this.wheels = wheels || 0; 
      this.color = color || ''; 
      this.speed = speed || 0; 
    }, 
    redAndFast = new Car(4,'red',230), 
    threeWheeler = new Car(3,'yellowstriped',110); 

或者,如果你想攀附在一些init像功能:

var Car = (function(){ 
    function car(wheels,color,speed){ 
      this.wheels = wheels || 0; 
      this.color = color || ''; 
      this.speed = speed || 0; 
    } 
    return { 
     init: function(w,c,s){ 
      return new car(w,c,s); 
     } 
    }; 
})(), 
redAndFast = Car.init(4,'red',230), 
threeWheeler = Car.init(3,'yellowstriped',110); 

但是,嘿,发生了什么事我context?你可能会问。那么,事实证明你毕竟不需要它。不是一个美丽而灵活的语言?

+0

哇! :)非常感谢您的时间! – punkbit 2011-05-08 22:23:36

+0

有人可以解释一下var Car =(function ...)()中的外括号是干什么的?我猜他们在解析时执行该功能,但为什么这是必需的? (是的,它似乎是必需的,否则'尝试执行init时没有引发任何方法init')我们总是需要在暴露内部函数时在解析时执行函数吗? – 2013-07-25 10:58:40

4
var Car = function() { 
    this.wheels = 4; 
    this.color = 'red'; 
    this.speed = 120; 
} 

var car = new Car(); 

对这些类型的任务最好使用普通构造函数。

+1

从我+1,我喜欢简单,简单的构造函数。让一个构造函数返回一个不是'this'的对象只是浪费了一个对象,并且造成了不必要的复杂性。构造函数**是** init函数。 :-) – RobG 2011-05-08 23:20:25

0

对象文字适用于单身人士。如果你想要一个可实例化的对象,你将需要学习如何工作,只使用函数对象。

相关问题