Javascript对象的文字,如何解决上下文?

时间:2011-05-08 20:50:58

标签: javascript closures this

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

    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);

3 个答案:

答案 0 :(得分: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);

<击> [编辑]我在想什么 ?如果你想要更多的Car实例,你将不得不使用真正的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发生了什么事?你可能会问。好吧,事实证明你毕竟不需要它。 javascript不是一种美观而灵活的语言吗?

答案 1 :(得分:4)

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

var car = new Car();

最好使用常规构造函数来完成这些任务。

答案 2 :(得分:0)

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